app.param()
Registers a callback that runs whenever a given route parameter is present.
Syntax
app.param(name, callback) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
name | string | Yes | The route parameter name to hook, e.g. `'id'`. |
callback | function | Yes | `(req, res, next, value)` invoked once per request when the param appears. |
Returns
Application — The app instance, for chaining.
Examples
app.param('userId', async (req, res, next, id) => {
const user = await findUser(id);
if (!user) return res.sendStatus(404);
req.user = user;
next();
});
app.get('/users/:userId', (req, res) => res.json(req.user));
Output
$ curl localhost:3000/users/1
{"id":"1","name":"Ada"}
app.param('id', (req, res, next, id) => {
if (!/^\d+$/.test(id)) return res.status(400).send('bad id');
next();
});
Output
$ curl localhost:3000/users/abc
bad id
Notes
Runs before any route handler that uses the parameter, so it is
ideal for centralizing resource loading and validation. It fires
once per request even if multiple routes share the param.