Query Parameters
Objectives
By the end of this lesson, you should be able to:
- Read query string values from
req.query - Provide a sensible default when a query parameter is missing
- Explain the difference between a route parameter and a query parameter
💡 Why this matters: Search terms, pagination, filters, sorting, all of it typically arrives as query parameters (
?q=nodejs&page=2), not route parameters. Module 4’surlmodule parsed these manually, Express does it automatically.
⚠️ A note on verification: every snippet and every response shown below was actually run and tested with real HTTP requests.
Reading Query Parameters
const express = require('express');
const app = express();
app.get('/search', (req, res) => {
res.json({
query: req.query.q || null,
page: req.query.page || '1',
allParams: req.query
});
});
app.listen(4004);
curl "http://localhost:4004/search?q=nodejs&page=2"
{"query":"nodejs","page":"2","allParams":{"q":"nodejs","page":"2"}}
curl "http://localhost:4004/search"
{"query":null,"page":"1","allParams":{}}
req.query is an object holding every query string parameter, already parsed, no manual splitting on ? or & needed (compare to Module 4’s URLSearchParams, which required that manually). Like route parameters, every value on req.query is a string. The req.query.page || '1' pattern from Module 3’s environment variables lesson reappears here, a clean way to provide a default when a parameter is optional.
Route Parameters vs Query Parameters
A route parameter (Lesson 4) identifies which resource, /users/42 means “user number 42,” it’s part of the route’s structure itself, and typically required. A query parameter modifies how to fetch or filter it, /search?q=nodejs&page=2 means “search for nodejs, page 2,” it’s optional extra detail, not part of the route’s identity. As a rule of thumb: if a request wouldn’t make sense without a piece of information, it’s a route parameter, if it’s optional refinement, it’s a query parameter.
Try It
- Write a route
/productsthat readsreq.query.categoryandreq.query.inStock, both optional, and returns them in a JSON response with sensible defaults for missing ones. - Test it with no query string, then with only
categoryset, then with both set. - Write a route
/users/:id/postscombining a route parameter (id) with a query parameter (req.query.sort), and confirm both are read correctly at once. - Explain, in your own words, why
/users/:iduses a route parameter but/search?q=termuses a query parameter, instead of the other way around.
Recap
req.queryholds every query string parameter as an already-parsed object, all values are strings.req.query.name || defaultValueis the standard pattern for an optional parameter.- Route parameters identify which resource, query parameters refine or filter how it’s fetched, both can appear in the same route.
Next lesson: serving static files directly from Express.