How to get GET (query string) variables in Express.js on Node.js?
When building an Express.js application, you can access query string parameters (i.e., variables appended in the URL after the ?
symbol) via req.query
inside your route handlers. Below is a concise guide on how to do it.
1. Basic Usage
If you have a URL like:
GET /search?term=nodejs&page=2
You can read the query parameters in your route like this:
app.get('/search', (req, res) => { const term = req.query.term; // "nodejs" const page = req.query.page; // "2" // Do something with 'term' or 'page' res.send(`You searched for "${term}" on page ${page}`); });
The req.query
object automatically parses any key-value pairs in the query string and makes them accessible as properties.
2. Default / Fallback Values
If the URL doesn’t include certain query parameters, req.query
will simply not have those properties. You can provide defaults or handle missing values:
app.get('/search', (req, res) => { const term = req.query.term || 'defaultTerm'; const page = req.query.page || 1; // ... });
3. Complex or Nested Query Parameters
By default, Express parses query parameters as simple key-value pairs. For example:
GET /users?role=admin&role=moderator
The result might be req.query.role
= 'moderator'
, or 'admin'
if you are using default Express query parsing without additional libraries.
If you need nested query structures or arrays, consider using a parsing library like qs, or configure Express to use a custom query parser. That said, for most use cases, the default req.query
is enough.
4. Example With All Steps
const express = require('express'); const app = express(); app.get('/search', (req, res) => { // req.query is an object containing all query string parameters const { term, page } = req.query; // Provide defaults const searchTerm = term || 'nodejs'; const currentPage = page || 1; res.json({ searchTerm, currentPage }); }); app.listen(3000, () => { console.log('Server listening on port 3000'); });
Now, if you visit:
http://localhost:3000/search?term=express&page=2
You’ll receive a JSON response like:
{ "searchTerm": "express", "currentPage": "2" }
Recommended Resources
Conclusion
To get GET (query) parameters in an Express.js application, reference req.query
in your route handlers. This provides you an object containing all the key-value pairs from the URL query string. If you need more advanced parsing (e.g., nested objects), configure a custom query parser or use a library like qs.