Route Parameters
Capture parts of the URL with :name and read them from req.params.
Syntax
app.get('/users/:id', (req, res) => req.params.id)Often part of a URL is dynamic, like a user id. Mark that segment with a colon, for example /users/:id. Express captures the value and puts it on req.params.
You can capture several parameters in one path, and each one appears on req.params by name.
Example
app.get('/users/:id', (req, res) => {
res.send('User id: ' + req.params.id);
});
app.get('/posts/:year/:month', (req, res) => {
const { year, month } = req.params;
res.send(`Posts from ${month}/${year}`);
});When to use it
- A blog routes GET /posts/:slug to look up an article by its URL-friendly slug stored in the database.
- An admin panel uses /users/:userId/roles/:roleId to address a specific role assigned to a specific user.
- A file-download endpoint at /files/:filename streams the requested file from disk using the :filename parameter.
More examples
Single route parameter
Captures the dynamic :id segment from the URL and returns it in the response.
app.get('/users/:id', (req, res) => {
const { id } = req.params;
res.json({ userId: id });
});Multiple route parameters
Shows two named parameters in a nested URL, both available on req.params.
app.get('/orgs/:orgId/teams/:teamId', (req, res) => {
const { orgId, teamId } = req.params;
res.json({ org: orgId, team: teamId });
});Optional parameter with regex constraint
Uses an inline regex constraint to route numeric IDs to one handler and string slugs to another.
// Only match numeric IDs
app.get('/products/:id(\\d+)', (req, res) => {
res.json({ productId: Number(req.params.id) });
});
// Non-numeric IDs fall through to this handler
app.get('/products/:slug', (req, res) => {
res.json({ slug: req.params.slug });
});
Discussion