Retrieve the GET query string parameters using Express
By Flavio Copes
The query string is the part that comes after the URL path and starts with a question mark ('?'). Let's see how to get the properties and their values.
The query string is the part that comes after the URL path, and starts with a question mark ?. Express exposes it through req.query, regardless of the HTTP method. Data sent in a request body uses req.body instead.
For example:
?name=flavio
Multiple query parameters can be added using &:
?name=flavio&age=35
How do you get those query string values in Express?
Express makes it very easy by populating the Request.query object for us:
const express = require('express')
const app = express()
app.get('/', (req, res) => {
console.log(req.query)
})
app.listen(8080)
This object is filled with a property for each query parameter.
If there are no query params, it’s an empty object.
This makes it easy to iterate on it using the for…in loop:
for (const key in req.query) {
console.log(key, req.query[key])
}
This will print the query property key and the value.
You can access single properties as well:
req.query.name //flavio
req.query.age //35
Repeated keys like ?tag=js&tag=node give you an array: req.query.tag is ['js', 'node'].
Nested query parameters in Express 5
Express 5 uses the “simple” query parser by default. Flat parameters like the ones above work exactly the same, but brackets don’t create nested objects anymore.
With ?user[name]=flavio&user[age]=35 you get this:
{ 'user[name]': 'flavio', 'user[age]': '35' }
If you want the nested object { user: { name: 'flavio', age: '35' } }, which is what Express 4 gave you, switch to the extended parser when you create the app:
const app = express()
app.set('query parser', 'extended')
One more change: req.query is read-only in Express 5. Assigning a new value to it does nothing (or throws in strict mode), so if you need to tweak the values, copy them first with const query = { ...req.query }.
The query string is only one of the things you can read from the request. Here’s a reference of all the request properties, and if your data comes from a form instead, see how to read POST parameters.
Want me to talk about your product? You can sponsor this site.