skip to content

In Express, why does auth middleware added with authRouter.use() also reject the public routes of a second router mounted on the same /users path?

level: seniorimportance: should knowfreq 30%

answer

  1. a router is just middleware
  2. the path decides, not the router
  3. a pathless use() inside a router
  4. first mounted, first entered

basics

~20 s

router.use(fn) without a path runs for every request that enters that router, and a router mounted with app.use('/users', ...) is entered by every /users request. Mounted first, authRouter rejects GET /users/42 before the second router's public route is ever tried.

solid answer

~50 s

In Express a router mounted with `app.use('/users', authRouter)` is one layer of the app's stack, and every request under `/users` enters it. Inside, `authRouter.use(requireUser)` has no path, so it matches every request that enters the router, not just the routes `authRouter` defines. For `GET /users/42`, the request enters `authRouter` first, `requireUser` answers 401, and `openRouter`, mounted second on the same path, is never consulted. With valid credentials the request passes, finds no matching route in `authRouter`, falls out of it, and `openRouter` serves it, which is why the bug hides in testing with a logged-in user. The Express reference warns about exactly this: when router-level middleware runs is defined by the path it is attached to, not by the router. The robust fix is to attach the guard to the routes that need it, `authRouter.get('/:id/edit', requireUser, handler)`, or to give the routers different mount paths.

code

javascript · 20 lines
javascript
const express = require('express');
const app = express();

function requireUser(req, res, next) {
  if (!req.get('authorization')) return res.sendStatus(401);
  next();
}

// Before: authRouter.use(requireUser) ran for every /users request,
// so GET /users/42 was rejected before openRouter was tried.
const authRouter = express.Router();
authRouter.get('/:id/edit', requireUser, (req, res) => res.send('edit form'));

const openRouter = express.Router();
openRouter.get('/:id', (req, res) => res.send(`profile ${req.params.id}`));

app.use('/users', authRouter);
app.use('/users', openRouter);

app.listen(3000);

go deeper

for a junior

Recall that a router is middleware, that a pathless router.use() runs for every request entering that router, and that routers on the same path are tried in mount order.

for a middle

Trace the dispatch of a request through two routers on one mount path and explain why credentials make the public route appear to work.

for a senior

Diagnose the anonymous-only 401, choose a fix that does not depend on mount order, and add tests that hit public endpoints without credentials.

for a principal

Set a convention for where guards live, per route, per prefix or per router, so access rules stay visible and do not depend on the order of app.use calls.

## A router is middleware with its own stack `express.Router()` returns a function that is valid middleware, so `app.use('/users', authRouter)` adds one layer to the app's stack. That layer matches every request whose path starts with `/users`, for any method, and hands it to the router, which walks **its own** stack of layers in registration order: its `router.use()` middleware and its `router.METHOD()` routes, interleaved exactly as they were registered. The point people miss is that a router does not first ask "do I have a route for this?". It walks its layers one by one, and a pathless `router.use(fn)` matches everything that entered the router. ## Tracing GET /users/42 Consider two routers mounted on the same path, in this order: ```js authRouter.use(requireUser); authRouter.get('/:id/edit', editHandler); openRouter.get('/:id', viewHandler); app.use('/users', authRouter); app.use('/users', openRouter); ``` A request for the public profile `GET /users/42` without credentials goes like this: 1. The app's first matching layer is the `authRouter` mount; the router trims `/users`, so inside it the path is `/42`. 2. `authRouter`'s first layer is `requireUser`, registered with `use` and no path, so it matches `/42`. 3. `requireUser` finds no credentials and answers 401 without calling `next()`, which ends the walk. 4. The `openRouter` mount, which holds the matching `/:id` route, is never reached. With credentials, step 3 calls `next()`, `/:id/edit` does not match `/42`, `authRouter` runs out of layers, the router exits, and the app tries the `openRouter` mount, which answers 200. The bug therefore only shows up for **anonymous** callers, which is exactly the population a logged-in developer never tests as. ## The rule the reference states The `router.use()` reference carries the warning in so many words: although these middleware functions are added via a particular router, **when they run is defined by the path they are attached to, not the router**, so middleware added via one router may run for other routers if its routes match. Grouping code into a router file groups it for *reading*; it does not scope its middleware to that file's routes. ## Why Express behaves this way Express has no global route table that it consults before running middleware. Dispatch is a linear walk: - the app's stack is a list of layers, each with a path and a function, tried in registration order; - a mounted router is one of those layers, and entering it starts a walk of its own list; - a layer registered with `use` matches on path prefix alone, for every method, and does not care whether any route below it will match; - leaving a router without an answer simply resumes the parent's walk at the next layer. That design is what makes routers composable, since any router can be mounted anywhere, but it also means a router's pathless middleware is a gate on the whole mount path for as long as that router is entered first. ## Fixes compared | Fix | How | Cost | |---|---|---| | Attach the guard per route | `authRouter.get('/:id/edit', requireUser, editHandler)` | Repeats the guard on each protected route, but the rule sits next to each endpoint | | Give the guard a path inside the router | `authRouter.use('/:id/edit', requireUser)` | Works, but the protected paths are now listed twice | | Separate mount paths | Mount the protected router at its own prefix | Changes public URLs, which may not be acceptable | | Swap mount order | Mount `openRouter` before `authRouter` | Fragile: anyone reordering `app.use` calls reopens the hole | Two tempting changes do **not** fix it: - **Moving `authRouter.use(requireUser)` below the routes.** For `/42`, `/:id/edit` still does not match, the walk reaches `requireUser`, and it still answers 401. - **Router options such as `mergeParams`.** They change how `req.params` is merged from the parent, not which requests the router's middleware sees. ## Making scope visible - Prefer guards attached to the routes or route groups they protect, so a reader can see an endpoint's protection where it is defined. - When a whole prefix must be protected, give it its own prefix and mount the guard with `app.use('/admin', requireUser, adminRouter)`, so the scope is the path itself. - Name your middleware functions, so stack traces and debug output show which layer answered. - Add tests that call each public endpoint **without credentials**; it is the test this bug fails. - Treat several routers mounted on the same path as a smell to review, because their pathless middleware leaks into one another's traffic in mount order.

  • Why does the public route work when the request carries valid credentials?
    The guard calls `next()`, `authRouter` has no route matching `/42`, so it runs out of layers and exits without answering. The app then tries its next matching layer, the `openRouter` mount, whose `/:id` route answers. Only anonymous requests are stopped, which is why the bug hides from logged-in testing.
  • Is mounting `openRouter` before `authRouter` a good fix?
    It works today, because public routes answer before the auth router is entered, but it makes security depend on the order of `app.use` calls. A later refactor that reorders imports or mounts silently reopens or widens the problem. Attaching the guard to the protected routes keeps the rule independent of mount order.

  • Middleware added with router.use() only runs for routes defined on that same router.
  • Express picks the router whose routes match before running any router middleware.
  • Mounting two routers on the same path makes the second one replace the first.
  • Moving router.use(auth) below the router's routes limits it to those routes.
  • The mergeParams option keeps one router's middleware away from another router's requests.