Route Parameters
Objectives
By the end of this lesson, you should be able to:
- Capture a dynamic segment of a URL using a route parameter
- Read a route parameter’s value from
req.params - Use multiple route parameters in a single route
💡 Why this matters: A real API needs routes like
/users/42or/posts/17/comments/3, where the number is dynamic, not a fixed path. Route parameters are how Express captures that dynamic piece without writing a separate route for every possible ID.
⚠️ A note on verification: every snippet and every response shown below was actually run and tested with real HTTP requests.
A Single Route Parameter
const express = require('express');
const app = express();
app.get('/users/:id', (req, res) => {
res.json({ userId: req.params.id });
});
app.listen(4004);
curl http://localhost:4004/users/42
{"userId":"42"}
A colon (:) before a segment name in a route path marks it as a route parameter, :id matches any value in that position, and Express makes it available as req.params.id. Route parameters are always strings, req.params.id here is "42", not the number 42, converting it (with Number()) is the caller’s responsibility if a number is needed.
Multiple Route Parameters
app.get('/users/:userId/posts/:postId', (req, res) => {
res.json({ userId: req.params.userId, postId: req.params.postId });
});
curl http://localhost:4004/users/7/posts/99
{"userId":"7","postId":"99"}
A single route can capture as many parameters as needed, req.params holds all of them, one property per named segment, keyed by the name after the colon.
Try It
- Write a route
/products/:productIdreturning{ productId: req.params.productId }as JSON, and test it with several different IDs. - Write a route
/categories/:categoryId/items/:itemIdcapturing both parameters, and confirm both appear correctly in the response. - Convert a captured
:idparameter to a number withNumber(req.params.id), and confirmtypeofthe converted value is"number"while the originalreq.params.idis"string". - Explain, in your own words, why route parameters are always strings, even when the URL segment looks like a number.
Recap
:namein a route path captures a dynamic URL segment, available asreq.params.name.- A route can have multiple parameters, all available on
req.paramsat once. - Route parameter values are always strings, converting them is the handler’s responsibility.
Next lesson: query parameters, reading values from a URL’s ?key=value portion.