skip to content

In Express 5, why is req.params.orgId undefined inside an express.Router mounted at /orgs/:orgId/users, and what does mergeParams change?

level: middleimportance: should knowfreq 48%

answer

  1. each router owns its params
  2. parent mount path captures
  3. Router constructor option
  4. child wins on conflict

basics

~20 s

Each express.Router fills req.params only from its own route paths, so a parameter in the parent's mount path is hidden from the child. express.Router({ mergeParams: true }) merges the parent's params in, and the child wins a conflict.

solid answer

~40 s

When a request enters a mounted `express.Router`, the router sets `req.params` from the paths **it** declares. The `:orgId` in `/orgs/:orgId/users` is part of the parent's mount path, so inside the child's `/:userId` route `req.params` holds only `userId`. Passing `mergeParams: true` to the `express.Router()` constructor tells the child to keep the parent's values and add its own; when both declare the same name, the child's value takes precedence. It is opt-in per router, defaulting to `false`, like the other two options, `caseSensitive` and `strict`. A `router.param('orgId', ...)` callback on the child still does not fire for the inherited value: param callbacks only trigger for parameters defined on that router's own routes.

code

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

const users = express.Router({ mergeParams: true });
users.get('/:userId', (req, res) => {
  res.json({ org: req.params.orgId, user: req.params.userId });
});

// Runs: the parameter is declared on the app's mount path
app.param('orgId', (req, res, next, orgId) => {
  req.orgSlug = orgId.toLowerCase();
  next();
});

app.use('/orgs/:orgId/users', users);
app.listen(3000);

go deeper

for a junior

Recall that a child router sees only its own params unless it is created with express.Router({ mergeParams: true }).

for a middle

Explain why routers isolate params, which value wins when names collide, and why a param callback on the child ignores inherited values.

for a senior

Show how you would trace a missing or wrong parameter in nested routers and place record loading on the router that owns the parameter.

for a principal

Decide whether nested resource routers should depend on parent parameters at all, or receive context another way, and how to name parameters across teams.

## The scenario A catalogue API serves users per organisation. The app mounts a users router under a path with a parameter: ```js const users = express.Router(); users.get('/:userId', (req, res) => { res.json({ org: req.params.orgId, user: req.params.userId }); }); app.use('/orgs/:orgId/users', users); ``` `GET /orgs/acme/users/7` returns `{ user: '7' }` with no `org`. Nothing is wrong with the mount: the parent did match `:orgId`. The value simply never reaches the child's `req.params`. ## Why the child cannot see it An `express.Router` is a self-contained routing system, a "mini-app" in the Express documentation's words. As the request travels through it, the router assigns `req.params` from the match of **its own** layers. The parent router's capture belongs to the parent's mount layer; when the child matches `/:userId`, it builds a fresh params object from that path alone. One benefit of this default is that a router can be mounted under any path without depending on what the parent called its parameters. ## What mergeParams does `mergeParams` is an option of the `express.Router()` constructor, default `false`. With it set: ```js const users = express.Router({ mergeParams: true }); ``` the child starts from the parent's params and adds its own on top. The rules: 1. Parent values arrive in the child, so `req.params.orgId` is `'acme'`. 2. The child's own captures are added next to them, so `req.params.userId` is `'7'`. 3. When both levels use the **same name**, the child's value takes precedence: with a mount at `/orgs/:id/users` and a child route `/:id`, `req.params.id` is the user id, not the org. 4. It applies one level at a time: each nested router that needs its parent's values must set `mergeParams` itself. Point 3 is the usual source of confusing bugs, so give nested parameters distinct names such as `orgId` and `userId`. ## The other Router options | Option | Default | Effect when `true` | | --- | --- | --- | | `mergeParams` | `false` | Keeps the parent's `req.params` values; child wins on conflict | | `caseSensitive` | `false` | `/Foo` and `/foo` become different paths | | `strict` | `false` | `/foo` and `/foo/` become different paths | These are per-router settings. The app-level settings `case sensitive routing` and `strict routing`, set with `app.set`, configure the app's own base router (and mounted sub-apps inherit them), and only if set before anything is registered on the app, because the app reads them once when it lazily creates that router. A router created separately with `express.Router()` does not inherit them; it uses whatever options were passed to its constructor. ## Param callbacks and inherited values `router.param(name, callback)` and `app.param(name, callback)` attach a trigger to a named parameter. Their scope is narrower than `mergeParams` suggests: - A param callback is **local to the router** that declares it. - It is not inherited by mounted routers. - It is **not triggered for parameters inherited** from a parent, even with `mergeParams: true`. So a `users.param('orgId', loadOrg)` declared on the child never runs for the org in the mount path. Put the org lookup where the parameter is declared, as an `app.param('orgId', ...)` on the parent, or as an ordinary middleware at the top of the child router that reads the merged `req.params.orgId`. ## Tracing a missing parameter When a nested route reports the wrong or a missing value, work through it in order: 1. Log `req.params` at the top of the child's handler to see exactly which keys arrived. 2. Check how the child was constructed: a bare `express.Router()` never sees parent values, whatever the mount path says. 3. Look for a **name collision** between the mount path and the child's own routes; with merging on, the child's capture silently replaces the parent's. 4. Check where any loading callback lives: on the child, a `router.param` for an inherited name is skipped without a warning. None of these mistakes raises an error at startup or at request time, which is why they survive into production until a handler reads the value. ## Checklist - The child needs a parent value: create it with `express.Router({ mergeParams: true })`. - Avoid reusing a parameter name across the mount path and the child's routes. - Expect `caseSensitive` and `strict` to be set per router, not inherited from the app. - Load parent-scoped records with a callback on the router that owns the parameter.

  • In Express 5, does app.set('strict routing', true) make a router created with express.Router() strict?
    No. That setting configures the app's own base router, and only if it is set before the first route or middleware is registered. A router built with `express.Router()` takes its behaviour from the options passed to the constructor, so it needs `express.Router({ strict: true })` to treat `/foo` and `/foo/` differently.
  • With mergeParams enabled in Express 5, how do you load the organisation once for every route in the child router?
    Either register `app.param('orgId', ...)` on the parent, where the parameter is declared, or put a plain middleware at the top of the child with `users.use(...)` that reads `req.params.orgId` and attaches the record. A `users.param('orgId', ...)` callback would never fire, because param callbacks ignore inherited parameters.

  • Parameters in a mount path always flow into the child router automatically.
  • mergeParams is an app setting turned on with app.set.
  • With mergeParams, the parent's value overrides the child's when names collide.
  • A router.param callback on the child fires for parameters inherited from the parent.
  • A router created with express.Router() inherits the app's strict routing setting.