In Express, when a router is mounted with app.use('/admin', adminRouter), what do req.url, req.baseUrl, req.path and req.originalUrl hold inside it?
answer
- mounting rewrites one of them
- the prefix moves into baseUrl
- one property never changes
- the match must stop at a slash
basics
~10 sInside a router mounted at /admin, Express strips the mount path from req.url and records it in req.baseUrl. For GET /admin/users/7?sort=desc, req.url is /users/7?sort=desc, req.path /users/7, req.baseUrl /admin, and req.originalUrl stays /admin/users/7?sort=desc.
solid answer
~40 s`app.use('/admin', adminRouter)` is a prefix mount: it matches `/admin` and anything under `/admin/`, for every HTTP method, but not `/administrator`, because the match has to end at a slash. When the request enters the router, Express trims the matched prefix off `req.url`, so the router's own paths are written relative to the mount, and puts the prefix in `req.baseUrl`. `req.path` is the pathname of the rewritten `req.url`, without the query string. `req.originalUrl` is never rewritten, so it always holds the full URL the client asked for. When the request leaves the router without being answered, Express restores `req.url` and `req.baseUrl` for the next layer. That is why a logger inside a router should print `req.originalUrl`, and why links built inside a router start from `req.baseUrl`.
code
javascript · 21 linesconst express = require('express');
const app = express();
const admin = express.Router();
admin.get('/users/:id', (req, res) => {
res.json({
url: req.url, // '/users/7?sort=desc'
path: req.path, // '/users/7'
baseUrl: req.baseUrl, // '/admin'
originalUrl: req.originalUrl, // '/admin/users/7?sort=desc'
});
});
app.use('/admin', admin);
// Reached by paths the router did not answer: the mount has been undone.
app.use((req, res) => {
res.status(404).json({ url: req.url, baseUrl: req.baseUrl }); // full url, ''
});
app.listen(3000);go deeper
Recall that app.use mounts on a prefix for any method, and that inside the router req.url loses the prefix while req.originalUrl keeps the full URL.
Explain the trim-and-restore mechanics: the prefix moves into req.baseUrl on entry and returns to req.url when the layer calls next, and nested mounts accumulate.
Show the production consequences: request logs missing the mount prefix, redirects that break when a router is remounted, and checks written against req.url instead of req.path.
Consider what a team standardises: which property logging, metrics labels and generated links must use, so routers stay relocatable without touching their code.
## What app.use path matching means `app.use(path, ...fns)` and `router.use(path, ...fns)` **mount** middleware on a path. The API reference describes the rule: the middleware runs when the *base* of the requested path matches `path`, and "a route will match any path that follows its path immediately with a `/`". So `app.use('/admin', fn)`: - matches `/admin`, `/admin/`, `/admin/users` and `/admin/users/7`; - does **not** match `/administrator`, because after the prefix the next character must be a `/` or the end of the path; - matches **every HTTP method**, unlike `app.get('/admin', fn)`, which matches only GET (and HEAD) and only that path, not paths below it; - defaults to `/` when the path is omitted, so `app.use(fn)` runs for every request. A router created with `express.Router()` is itself valid middleware, so mounting one is just a special case of this rule. ## What the router rewrites on the way in When a request enters a layer mounted on a path, the router trims the matched prefix off `req.url` and appends it to `req.baseUrl`. For `GET /admin/users/7?sort=desc` against `app.use('/admin', adminRouter)`: | Property | In app-level middleware before the mount | Inside `adminRouter` | In app middleware after the router falls through | |---|---|---|---| | `req.url` | `/admin/users/7?sort=desc` | `/users/7?sort=desc` | `/admin/users/7?sort=desc` | | `req.path` | `/admin/users/7` | `/users/7` | `/admin/users/7` | | `req.baseUrl` | `''` | `/admin` | `''` | | `req.originalUrl` | `/admin/users/7?sort=desc` | `/admin/users/7?sort=desc` | `/admin/users/7?sort=desc` | Three definitions keep the table straight: - **`req.url`** is inherited from Node's request object, and mounting rewrites it so the router can match its own paths, such as `/users/:id`, relative to where it was mounted. - **`req.baseUrl`** is "the URL path on which a router instance was mounted", as the matched string. Mount on a pattern such as `['/hel{l}o']` and a request to `/helo/x` gets `req.baseUrl` `/helo`, not the pattern. - **`req.originalUrl`** is the request URL as received; the reference describes it as a combination of `req.baseUrl` and `req.url`, and Express never rewrites it. ## Restoring on the way out The rewrite is scoped to the mounted layer. The router's `next` undoes it before it looks for the next layer: 1. On entering a mounted layer, the router saves the removed prefix, shortens `req.url` and extends `req.baseUrl`. 2. When that layer calls `next()` or `next(err)`, the router puts the prefix back on `req.url` and restores the parent's `req.baseUrl`. 3. When a router exits altogether, `req.baseUrl`, `req.params` and `req.next` are restored to the values the parent had. So middleware registered after the router, such as an app-level 404 handler, sees the full `req.url` again and an empty `req.baseUrl`. ## Nested mounts accumulate Mounts compose. With `outer.use('/users', inner)` and `app.use('/admin', outer)`, a handler in `inner` serving `GET /admin/users/9` sees `req.baseUrl` `/admin/users`, `req.url` `/9` and `req.originalUrl` `/admin/users/9`. A whole Express app can be mounted too; then `subApp.mountpath` holds the *pattern* it was mounted on, while `req.baseUrl` holds the matched string. ## Which property to use for what - **Logging and metrics:** use `req.originalUrl`. A logger mounted inside a router that prints `req.url` loses the mount prefix. morgan's `:url` token already prefers `req.originalUrl`. - **Links and redirects relative to the mount:** build them from `req.baseUrl`, so the router keeps working if it is remounted at `/v2/admin`. - **Path checks inside the router:** use `req.path`; it is relative to the mount and free of the query string. - **Rewriting:** change `req.url` if you must route internally, never `req.originalUrl`; the reference notes that keeping the original is exactly what lets `req.url` be rewritten freely. ## A common bug: checks written against req.url Code that moves into a router often keeps checks written for the app level, and they silently stop matching: - `if (req.url === '/health')` fails for `/health?probe=1`, because `req.url` keeps the query string; compare `req.path` instead. - `if (req.url.startsWith('/admin'))` inside a router mounted at `/admin` is never true, because the prefix was trimmed; inside the router, the mount is in `req.baseUrl`. - A redirect to a hard-coded `'/admin/login'` breaks when the router is remounted; `res.redirect(req.baseUrl + '/login')` follows the mount. None of these throw. They just send requests down the wrong branch, which is why they survive until someone remounts a router. ## app.use versus app.METHOD Routes registered with `app.get`, `app.post` or `router.get` are not prefix mounts. They match the whole remaining path, they do not trim `req.url`, and they do not change `req.baseUrl`. That is the practical difference worth stating in an interview: `app.use` is for a stack that should see a whole subtree on any method, and `app.METHOD` is for one endpoint.
- How does `req.baseUrl` differ from `app.mountpath`?`req.baseUrl` is per request and holds the matched string, so a router mounted on `['/greet', '/hel{l}o']` reports `/greet`, `/hello` or `/helo` depending on the request. `app.mountpath` belongs to a mounted sub-app and holds the pattern or list of patterns it was mounted on. Use `req.baseUrl` to build URLs for the current request.
- Why does a 404 handler registered after the routers still see the full path in `req.url`?The prefix trim is undone as soon as the mounted layer calls `next()`. The router puts the removed prefix back on `req.url` and restores the parent's `req.baseUrl` before it searches for the next layer, so app-level middleware after the mount sees the request exactly as it arrived.
- app.use('/admin', fn) also matches /administrator because it is a prefix match.
- req.originalUrl is the path relative to the router's mount point.
- Inside a mounted router, req.url still includes the mount path.
- app.use('/admin', fn) runs only for GET requests, like app.get.
- req.baseUrl returns the pattern the router was mounted on, such as /hel{l}o.