router.param()
Registers a parameter callback scoped to a router.
Syntax
router.param(name, callback) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
name | string | Yes | The route parameter name to hook. |
callback | function | Yes | `(req, res, next, value)` run once when the param is matched. |
Returns
Router — The router, for chaining.
Examples
const router = express.Router();
router.param('id', async (req, res, next, id) => {
const book = await findBook(id);
if (!book) return res.sendStatus(404);
req.book = book;
next();
});
router.get('/books/:id', (req, res) => res.json(req.book));
app.use('/api', router);
Output
$ curl localhost:3000/api/books/1
{"id":"1","title":"SICP"}
router.param('slug', (req, res, next, slug) => {
req.slug = slug.toLowerCase();
next();
});
Notes
Same behavior as `app.param` but limited to the router, so resource
loading lives next to the routes that use it. Runs before the
route's handlers and only once per request per param.