Route Parameters and Query Strings
8 min read
Route Parameters and Query Strings
Route parameters are named URL segments prefixed with a colon. Express parses them automatically and exposes them on req.params as an object of strings.
js
app.get("/posts/:postId/comments/:commentId", (req, res) => {
const { postId, commentId } = req.params;
res.json({ postId, commentId });
});Query strings appear after the ? in a URL and are parsed into req.query. Every value arrives as a string (or an array of strings for repeated keys), so you must convert to numbers explicitly when needed.
js
// GET /products?category=shoes&page=2
app.get("/products", (req, res) => {
const category = req.query.category as string;
const page = Number(req.query.page) || 1;
res.json({ category, page });
});Never trust req.params or req.query values directly. Always validate and sanitise them before using in database queries to prevent injection attacks.
Ready to test yourself?
Practice Express— quiz & coding exercises