Route Parameters & Query Strings
URLs carry data in two places: inside the path (/books/42) and after the question mark (/books?author=le-guin&page=2). Express parses both for you and exposes them as req.params and req.query.
Path parameters: req.params
A segment that starts with : captures whatever text sits in that position:
const express = require('express');
const app = express();
app.get('/authors/:authorId/books/:bookId', (req, res) => {
res.json(req.params);
});
const server = app.listen(0, async () => {
const res = await fetch(`http://localhost:${server.address().port}/authors/7/books/1984`);
const params = await res.json();
console.log(params);
console.log(typeof params.bookId);
server.close();
});{ authorId: '7', bookId: '1984' }
string
Note: Parameter values are always strings. Convert them yourself (
Number(req.params.id)) and check the result —Number('abc')isNaN.
Parameters are URL-decoded, so /tags/caf%C3%A9 gives req.params.tag === 'café'.
Validating a numeric id
A common pattern converts the id and rejects anything that isn't a positive integer:
const express = require('express');
const app = express();
const books = new Map([[1, 'Dune'], [2, 'Kindred']]);
app.get('/books/:id', (req, res) => {
const id = Number(req.params.id);
if (!Number.isInteger(id) || id < 1) {
return res.status(400).json({ error: 'id must be a positive integer' });
}
if (!books.has(id)) return res.status(404).json({ error: `book ${id} not found` });
res.json({ id, title: books.get(id) });
});
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
for (const path of ['/books/2', '/books/9', '/books/two', '/books/1.5']) {
const res = await fetch(base + path);
console.log(path.padEnd(11), res.status, await res.text());
}
server.close();
});/books/2 200 {"id":2,"title":"Kindred"}
/books/9 404 {"error":"book 9 not found"}
/books/two 400 {"error":"id must be a positive integer"}
/books/1.5 400 {"error":"id must be a positive integer"}
app.param() — run code for every route with a parameter
If many routes use :userId, app.param lets you load the user once and attach it to req:
app.param('userId', (req, res, next, value) => {
const user = users.get(Number(value));
if (!user) return res.status(404).json({ error: 'user not found' });
req.user = user;
next();
});
app.get('/users/:userId', (req, res) => res.json(req.user));
app.get('/users/:userId/orders', (req, res) => res.json(ordersOf(req.user)));Query strings: req.query
Everything after ? is parsed into req.query. Repeated keys become arrays:
const express = require('express');
const app = express();
app.get('/search', (req, res) => res.json(req.query));
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
const queries = ['?q=express', '?q=node%20js&page=2', '?tag=api&tag=rest', ''];
for (const qs of queries) {
const res = await fetch(base + '/search' + qs);
console.log((qs || '(none)').padEnd(19), await res.text());
}
server.close();
});?q=express {"q":"express"}
?q=node%20js&page=2 {"q":"node js","page":"2"}
?tag=api&tag=rest {"tag":["api","rest"]}
(none) {}
| Request | req.query |
|---|---|
/search?q=express |
{ q: 'express' } |
/search?tag=a&tag=b |
{ tag: ['a', 'b'] } — an array! |
/search?filter[x]=1 |
{ 'filter[x]': '1' } — Express 5 uses the simple parser |
/search |
{} |
Note: Express 4 used the
qslibrary by default, which turnedfilter[x]=1into nested objects. Express 5 switched to Node's simplerquerystringparser. If you really need nested objects, setapp.set('query parser', 'extended').
Defensive query parsing
Because a key may be missing, a string, or an array, write small helpers instead of trusting req.query:
const express = require('express');
const app = express();
const first = (v) => (Array.isArray(v) ? v[0] : v);
const toInt = (v, fallback) => {
const n = Number.parseInt(first(v), 10);
return Number.isNaN(n) ? fallback : n;
};
app.get('/items', (req, res) => {
const page = Math.max(1, toInt(req.query.page, 1));
const limit = Math.min(50, toInt(req.query.limit, 10));
res.json({ page, limit });
});
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}/items`;
for (const qs of ['', '?page=3&limit=20', '?page=-4&limit=500', '?page=x&page=2']) {
const res = await fetch(base + qs);
console.log((qs || '(none)').padEnd(19), await res.text());
}
server.close();
});(none) {"page":1,"limit":10}
?page=3&limit=20 {"page":3,"limit":20}
?page=-4&limit=500 {"page":1,"limit":50}
?page=x&page=2 {"page":1,"limit":10}
Params vs query: which one?
| Use a path parameter when… | Use a query string when… |
|---|---|
it identifies a resource: /users/42 |
it modifies a listing: ?sort=name |
| the URL is meaningless without it | it is optional and has a default |
| there is exactly one value | there can be zero, one or many values |
Test yourself
For route /orders/:id and request /orders/15, what is typeof req.params.id?
- number
- string
- bigint
- object
What is req.query.color for /shirts?color=red&color=blue?
- 'red'
- 'blue'
- ['red', 'blue']
- 'red,blue'
Which is the better design for 'page 3 of the product list'?
- /products/page/3
- /products?page=3
- /products/3
- /page3/products