In Express 5, what do app.param callbacks and next('route') each do, and when does a param callback run during a request?
answer
- triggers keyed by parameter name
- before the route's handlers
- once per request per value
- skip to the next route
basics
~20 sapp.param(name, callback) runs once per request, before the handlers of any matching route that declares that parameter, which suits loading a record by id; next('route') skips the remaining callbacks of the current route and resumes matching at the next route.
solid answer
~40 s`app.param(name, callback)` registers a trigger called as `callback(req, res, next, value, name)` whenever a route on that router declares the parameter. It runs before any handler of that route, and only once per request for the same value, even when several matching routes use the parameter, so it is the natural place to load a product by `:sku` or reject an unknown one. It is local to its router and ignores parameters inherited from a parent. In Express 5, `app.param` takes a name or an array of names while `router.param` takes one string. `next('route')`, called inside a route callback, skips that route's remaining callbacks and carries on with the next matching route; in middleware registered with `app.use` it behaves like plain `next()`.
go deeper
Recall that app.param runs code for a named parameter before the handlers, and that next('route') hands the request to the next matching route.
Explain the once-per-request rule, the callback's argument order, its router-local scope, and why next('route') does nothing special in app.use middleware.
Show when a param callback is the right place for loading and rejecting records, and how errors and early responses from it behave in production.
Judge whether param callbacks or explicit per-route middleware make a large codebase easier to read and test, and set the team's rule.
## Two tools for one job Many routes in a catalogue API start the same way: read `:sku` from the path, load the product, and stop with a 404 if it does not exist. Express offers two route-level tools that keep this logic out of every handler: - **`app.param`** (and `router.param`) attaches work to a **parameter name**, wherever it appears. - **`next('route')`** lets a route callback **step aside** so a later route can handle the request. ## app.param: a trigger on a parameter name ```js app.param('sku', async (req, res, next, sku) => { const product = await catalogue.findBySku(sku); if (!product) return res.status(404).json({ error: 'unknown sku' }); req.product = product; next(); }); app.get('/products/:sku', (req, res) => res.json(req.product)); app.put('/products/:sku', (req, res) => res.json(req.product)); ``` The callback receives `req`, `res`, `next`, the parameter's **value** and its **name**, in that order. Its behaviour, as the Express 5 reference and the router source describe it: 1. It runs **before any handler** of a route whose path declares the parameter. 2. It runs **once per request** for a given value, even when several matching routes declare the same parameter and call `next()` through to each other. 3. It is **local** to the router that registered it: it is not inherited by mounted routers and does not fire for parameters inherited from a parent router. 4. Calling `next(err)`, throwing, or returning a rejected promise sends the error to the error-handling middleware. When the name is an array, as in `app.param(['id', 'page'], fn)`, Express registers the callback for each name in order. `router.param()` in Express 5 accepts **only a string**; passing an array throws `TypeError: argument name must be a string`, so register each name with its own call. The older `app.param(fn)` form, which customised how `app.param` itself worked, no longer exists. ## next('route'): skip the rest of this route A route can have several callbacks. Calling `next()` moves to the next callback of the **same route**; calling `next('route')` abandons the current route and lets matching continue with the **next registered route** whose method and path fit. ```js app.get('/products/:sku', (req, res, next) => { if (req.query.view === 'legacy') return next('route'); res.json(req.product); }, auditView); app.get('/products/:sku', (req, res) => { res.json({ legacy: true, sku: req.params.sku }); }); ``` Here `auditView` is skipped for legacy requests, and the second route answers them. The parameter callback for `sku` does not run again for the second route, because the value is unchanged. ## Where each signal works | Called in | `next()` | `next('route')` | | --- | --- | --- | | A callback of `app.get`, `app.all`, `router.METHOD` or an `app.route` chain | Next callback of this route | Skips to the next matching route | | Middleware registered with `app.use` or `router.use` | Next matching layer | Same as `next()` | | An `app.param` callback | Continues to the route's handlers | Not a documented use | `next('route')` is meaningful only where there is a route to leave; in plain middleware the router treats it as an ordinary `next()`. Leaving a whole router at once is a different signal, `next('router')`, which belongs with the middleware material. ## Early responses and errors A param callback is a full participant in the request, not just a loader: - It may **respond** itself, as the 404 branch above does. If it never calls `next()`, none of the route's handlers run. - It may call **`next(err)`**, throw, or return a rejected promise; Express 5 forwards each of these to the error-handling middleware and skips the route's handlers. - With an **array of names**, calling `next()` from the callback for every name except the last runs the callback for the next declared name; after the last one, `next()` continues to the route. - Because the result is cached per value, an expensive lookup in a param callback is paid once per request even when routes fall through to each other with `next()` or `next('route')`. ## When to choose which - Use **`app.param`** to load or check a record once for every route that names the parameter. - Use **`next('route')`** when a precondition decides that another route, registered later, should answer. - Prefer a plain middleware on the route when the work is not tied to a single parameter name. - Keep param callbacks on the router that declares the parameter; a child router cannot rely on a parent's callbacks.
- In Express 5, does an app.param callback run again when a second matching route uses the same parameter?Not for the same value. Express records that the callback ran for that parameter and value in the current request and reuses the result, so a log line inside it appears once even when two `/user/:id` routes both match and call `next()`. It would run again only if the value changed.
- What happens in Express 5 when an async app.param callback rejects?The router catches the returned promise's rejection and passes the error on as if `next(err)` were called, so the request skips the route handlers and reaches the error-handling middleware. A synchronous throw inside the callback takes the same path.
- An app.param callback runs once for every matching route that declares the parameter.
- next('route') ends the request with a 404 straight away.
- next('route') inside app.use middleware skips the route that follows it.
- router.param in Express 5 accepts an array of names like app.param.
- A param callback on the app also fires for parameters declared in mounted routers' routes.
Assumes Express 5: router.param accepts only a single string name and the app.param(fn) form is gone; Express 4 accepted both.