skip to content

In Express, how does next('router') let middleware bail out of a router mounted at /admin, and what runs after it?

level: middleimportance: nice to knowfreq 28%

answer

  1. a string signal, not an error
  2. leaves the whole router instance
  3. the parent's stack carries on
  4. next('route') skips less

basics

~20 s

Calling next('router') inside an Express router skips every remaining layer of that router and hands the request back to the parent with no error. The parent then runs its next matching layer, such as a fallback mounted after the router that answers 401.

solid answer

~40 s

In Express, `next('router')` is a signal, not an error. When middleware or a route handler inside a router calls it, the router stops walking its own stack and calls its completion callback with no error, so control returns to the stack the router was mounted in. The Express guide's pattern is a precondition: `router.use()` checks a header and calls `next('router')` when it is missing, and `app.use('/admin', router, (req, res) => res.sendStatus(401))` answers whatever falls out. Because no error is passed, error handlers do not run; the parent's next ordinary layer does. It differs from `next('route')`, which only skips the rest of the current route's callbacks and is honoured only in callbacks registered with `app.METHOD()` or `router.METHOD()`; in a `router.use()` middleware it behaves like `next()`.

code

javascript · 16 lines
javascript
const express = require('express');
const app = express();
const admin = express.Router();

// Precondition for the whole router: without a valid token, leave it.
admin.use((req, res, next) => {
  const token = req.get('x-admin-token');
  if (!token || token !== process.env.ADMIN_TOKEN) return next('router');
  next();
});
admin.get('/reports', (req, res) => res.json({ reports: [] }));

// Runs for requests the router declined, and for any it did not answer.
app.use('/admin', admin, (req, res) => res.sendStatus(401));

app.listen(3000);

go deeper

for a junior

Recall that next('router') leaves the current router and next('route') skips the rest of one route, and that neither is an error.

for a middle

Explain the mechanics: the router completes with no error, restores baseUrl and params, and the parent's next matching layer runs, so a fallback after the router decides the response.

for a senior

Spot the traps: a fallback that turns real 404s into 401s, next('router') at the app level producing a 404, and next('route') silently acting like next() in use() middleware.

for a principal

Judge when a router-wide precondition with fallthrough is clearer than per-route guards or errors, given how hard fallthrough paths are to read in a large route table.

## Four ways to call next Express's `next` accepts an argument, and three special cases are worth knowing apart: | Call | Effect | Where it is honoured | |---|---|---| | `next()` | Run the next matching layer of the current stack | Everywhere | | `next('route')` | Skip the remaining callbacks of the current route and try the next matching route | Callbacks registered with `app.METHOD()` or `router.METHOD()`; elsewhere it acts like `next()` | | `next('router')` | Skip everything left in the current router and return to the parent stack, with no error | Middleware and route handlers inside a router | | `next(err)` | Skip ordinary middleware and run error-handling middleware | Everywhere | The two strings are **signals**: the router recognises them by value and never treats them as errors. Any other truthy argument is an error. ## What happens inside the router The behaviour is visible in the router's `handle` loop: 1. A middleware in the router calls `next('router')`. 2. The router undoes the URL rewrite it applied for the current mounted layer, if any. 3. Seeing the `'router'` signal, it schedules its own completion callback with `null`, meaning "finished, no error", instead of looking at further layers. 4. The completion callback restores the parent's `req.baseUrl`, `req.params` and `req.next`. 5. The parent stack continues with its next matching layer, exactly as if the router had run out of layers without answering. The same signal works from a route handler: the route passes `'router'` up to its router, which exits as above. The router's README describes it as exiting "the current router instance completely". ## The guard-and-fallback pattern The Express guide shows the canonical use: give a router a precondition, and let anything that fails it fall through to a handler mounted after the router on the same path. ```js admin.use((req, res, next) => { if (!req.headers['x-auth']) return next('router'); next(); }); app.use('/admin', admin, (req, res) => res.sendStatus(401)); ``` - Requests without the header leave `admin` immediately and reach the 401 callback. - Requests with the header run through `admin`; if one of its routes answers, the fallback never runs. - Requests with the header that match **no** route in `admin` also fall out and get 401, not 404, because the fallback catches everything the router does not answer. Put a 404 handler at the end of the router if that distinction matters. Note the `return` in `return next('router')`. Without it, the function would go on to call `next()` as well, and the router would be asked to continue twice for one request: once out of the router and once into its next layer. Each branch of a precondition should call `next` exactly once. A second use is a **feature or version router**: mount a new router and the old one on the same path, and let the new one call `next('router')` when the request does not qualify, so the old one handles it. ## Edge cases - **At the app level.** Middleware registered directly with `app.use()` lives in the app's base router, so `next('router')` exits the app's router itself. Express's final handler then answers `404 Cannot GET /path`, and any routes registered on the app after that middleware never run. - **No error handlers.** Because the router completes with `null`, four-argument error handlers are skipped like any other error handler on the success path. - **`next('route')` in `router.use()`.** The router clears the `'route'` value before choosing the next layer, so in middleware registered with `use` it behaves like plain `next()`. The guide is explicit that `next('route')` works only in callbacks loaded with `app.METHOD()` or `router.METHOD()`. - **Nested routers.** `next('router')` exits only the innermost router whose stack is running; the router it is mounted in carries on. ## When to reach for it - Use it when a **whole router** should be skipped for a request, such as a precondition, a feature flag or a version gate, and something after it in the parent should decide what happens. - Prefer a guard attached to the routes that need it, such as `router.get(path, guard, handler)`, when only some endpoints need protection; that keeps the rule next to the endpoints it covers. - Prefer `next(err)` with an error carrying a status when the request should *fail* rather than be handed to someone else, so your error handler shapes the response. - Remember that a fallthrough handler mounted after the router turns unanswered paths into whatever it sends, which can hide genuine 404s.

  • What happens when middleware registered directly with `app.use()` calls `next('router')`?
    It exits the app's own base router. Express's final handler then answers `404 Cannot GET /path`, and any routes or middleware registered on the app after that point never run for the request, even if they would have matched.
  • Does `next('router')` reach the error-handling middleware?
    No. The router treats `'router'` as a signal and completes with no error, so the parent continues on its ordinary path and four-argument error handlers are skipped. To fail the request through the error handler, call `next(err)` with an error object instead.

  • next('router') passes an error, so the error-handling middleware runs next.
  • next('route') in a router.use() middleware exits the whole router.
  • next('router') skips only the current route's remaining callbacks.
  • After next('router') Express always answers 404 immediately.
  • next('router') ends the request, so nothing mounted after the router runs.