The Analogy: The Office-Building Mailroom
Picture the ground-floor mailroom of a large office building. Every letter and parcel that arrives for the whole building lands here first, in one heap. The mailroom clerks do not run each envelope up to its recipient themselves. Instead they sort the incoming pile into labeled canvas sacks, one sack per floor, and hand each sack to that floor's own reception desk. The third-floor sack goes to the third-floor desk, the fifth-floor sack to the fifth-floor desk, and so on.
Each floor's desk is a self-contained little post office. It knows nothing about the other floors; it only knows the room numbers on its own floor. When the third-floor desk receives its sack, it reads the room number on each item and walks it to room 301, 302, or 305 on that floor alone. The same room number, say "room 5", can exist on every floor with no confusion, because the ground-floor mailroom already decided which floor's desk each item belongs to before the room number is ever read.
This division of labor is what keeps a big building manageable. The ground-floor clerks maintain one simple rule set: which floor does this go to. Each floor desk maintains its own small rule set: which room on this floor. A floor can rearrange its internal rooms, add a desk, or hire a new clerk without the ground-floor mailroom changing at all, because the only contract between them is the floor label on the sack.
Now suppose one floor's desk has a sloppy filing rule. Its clerk has posted two overlapping notices: "any item labeled room-something goes to the intern" and, below it, "items labeled room 101 go to the manager". Because the clerk reads notices top to bottom and stops at the first that fits, every item, including the ones for room 101, is handed to the intern; the manager's rule is never reached. The desk is not broken and throws no error; it simply shadows one rule with a more general one placed above it, and mail silently goes to the wrong person.
Syntax or Core Structure
An Express Router is a miniature, self-contained application: it has its own stack of middleware and routes, but no server of its own. You create one with express.Router(), attach routes to it exactly as you would to app, and then mount it onto the main application at a path prefix with app.use(). The prefix is stripped before the router sees the URL, so the router only deals with paths relative to its own mount point.
Creating and Mounting a Router
const express = require('express');
const app = express();
const salesRouter = express.Router();
salesRouter.get('/', function (req, res) {
res.send('sales directory');
});
// Mount the router at a prefix. A request to /sales/
// is handled by the router's '/' route.
app.use('/sales', salesRouter);
Splitting Routers Across Files
In real projects each router lives in its own module and is exported, so app.js stays a short table of mount points instead of a thousand-line pile of routes.
// routes/sales.js
const express = require('express');
const router = express.Router();
router.get('/desk/:id', function (req, res) {
res.json({ floor: 'sales', desk: req.params.id });
});
module.exports = router;
// app.js
const salesRouter = require('./routes/sales');
app.use('/sales', salesRouter);
The :id segment is a route parameter: a named placeholder that matches any single path segment and is exposed on req.params. It is how one route definition serves many concrete URLs.
Technical Depth: Mount Points, Parameters, and Match Order
One Relative Path, Many Mount Points
The whole point of the mailroom is that each floor desk uses the same simple internal numbering, and the prefix decides which desk runs. Two routers can both define /desk/:id; the mount prefix keeps them apart. This server mounts a sales desk and an HR desk that share identical relative routes:
const express = require('express');
const app = express();
const salesRouter = express.Router();
salesRouter.get('/', function (req, res) {
res.json({ floor: 'sales', view: 'directory' });
});
salesRouter.get('/desk/:id', function (req, res) {
res.json({ floor: 'sales', desk: req.params.id });
});
const hrRouter = express.Router();
hrRouter.get('/', function (req, res) {
res.json({ floor: 'hr', view: 'directory' });
});
hrRouter.get('/desk/:id', function (req, res) {
res.json({ floor: 'hr', desk: req.params.id });
});
app.use('/sales', salesRouter);
app.use('/hr', hrRouter);
The router mounted at /sales answers its / route when the full URL is /sales:
Output:
{"floor":"sales","view":"directory"} [200]
A request to /sales/desk/7 strips the /sales prefix, leaving /desk/7 for the sales router, which captures 7 as req.params.id:
Output:
{"floor":"sales","desk":"7"} [200]
The identical relative path under the other mount, /hr/desk/7, is handled by the HR router instead, proving the two share a path shape but not a handler:
Output:
{"floor":"hr","desk":"7"} [200]
Router-Level Middleware Is Scoped
A router can carry its own middleware with router.use(), and that middleware runs only for requests routed into that router, never for the rest of the app. It is the floor desk's own house rule. Here a /secure router stamps a zone that the public lobby route never sees:
const secure = express.Router();
secure.use(function (req, res, next) {
req.zone = 'restricted';
next();
});
secure.get('/vault', function (req, res) {
res.json({ zone: req.zone, item: 'ledger' });
});
app.get('/lobby', function (req, res) {
res.json({ zone: req.zone || 'public', item: 'brochure' });
});
app.use('/secure', secure);
The lobby route is outside the router, so req.zone was never set and falls back to 'public':
Output:
{"zone":"public","item":"brochure"} [200]
A request into the mounted router runs the router middleware first, so req.zone is present:
Output:
{"zone":"restricted","item":"ledger"} [200]
Chaining Methods with router.route()
When several HTTP methods share one path, router.route() lets you attach them in a single chained statement instead of repeating the path. This desk router exposes /badge for both reading and creating:
const router = express.Router();
router.route('/badge')
.get(function (req, res) {
res.json({ action: 'read', badge: 'blank' });
})
.post(function (req, res) {
res.json({ action: 'create', badge: 'issued' });
});
app.use('/desk', router);
A GET to /desk/badge hits the chained .get handler:
Output:
{"action":"read","badge":"blank"} [200]
A POST to the same path hits the .post handler instead, with no duplicated path string:
Output:
{"action":"create","badge":"issued"} [200]
Nested Routers with mergeParams
A router can be mounted at a path that itself contains a parameter, such as /building/:building/floors. By default the inner router cannot see :building; you must create it with mergeParams: true so the parent's captured parameters are merged into the child's req.params.
const floors = express.Router({ mergeParams: true });
floors.get('/:floor', function (req, res) {
res.json({ building: req.params.building, floor: req.params.floor });
});
app.use('/building/:building/floors', floors);
A request to /building/west/floors/3 binds west from the mount path and 3 from the inner route, and both appear on req.params because the flag merged them:
Output:
{"building":"west","floor":"3"} [200]
Match Order Within a Router
Inside a single router, routes are tested top to bottom and the FIRST match wins, exactly like the clerk reading notices in order. Express does not gather every candidate and then pick the most specific one; it stops at the very first route whose method and path pattern both match, which is why physical placement in the file decides behavior.
| Registration order | Incoming URL | Which route answers |
|---|---|---|
| :name before literal | /room/101 | The :name route shadows the literal |
| literal before :name | /room/101 | The literal route |
| :name before literal | /room/lobby | The :name route, the only match |
Real World Example: A Route Collision You Can See
This router registers a parameterized route /room/:name BEFORE a literal route /room/101. The intent might have been to give room 101 special handling, but because the parameter route is registered first and matches any single segment, it captures 101 too and the literal route below it is dead code.
const express = require('express');
const app = express();
const router = express.Router();
router.get('/room/:name', function (req, res) {
res.json({ matched: 'named', name: req.params.name });
});
router.get('/room/101', function (req, res) {
res.json({ matched: 'literal-101' });
});
app.use('/office', router);
A request to /office/room/101 is captured by the :name route, which was registered first. The response reports it matched the named route and bound 101 as the parameter value, so the literal route never ran:
Output:
{"matched":"named","name":"101"} [200]
A request to /office/room/lobby is handled by the same :name route, which is the behavior actually intended for every value except the special case:
Output:
{"matched":"named","name":"lobby"} [200]
The lesson is that route order is a real part of your program's meaning, not a stylistic detail. The two flaws here are worth naming precisely. First, the literal /room/101 route is unreachable: it will never execute for any request, yet it sits in the file looking like working code, which will mislead the next reader. Second, the fix is order-sensitive and fragile: moving the literal route above the parameter route makes it work, but nothing in the code documents that the ordering is load-bearing, so a well-meaning cleanup that sorts routes alphabetically would silently reintroduce the bug.
Common Mistakes
- Registering a parameter route before a more specific literal route. Because the first match wins,
/room/:nameplaced above/room/101swallows the literal path and the specific handler becomes dead code, as demonstrated above.
- Forgetting that the mount prefix is stripped. Inside a router mounted at
/sales, the route for the sales desk must be written as/desk, not/sales/desk. Repeating the prefix produces a route that can never match.
- Expecting router-level middleware to run for the whole app. A function added with
router.use()runs only for requests routed into that router. Middleware that must run everywhere belongs onapp, not on one router.
- Losing req.params across mount boundaries. By default a child router does not see the parent's route parameters. Creating the router without
express.Router({ mergeParams: true })leaves the parent's captured parameters missing fromreq.params.
- Forgetting to export the router. Ending a route module without
module.exports = routermeans the mounting call receivesundefined, and Express complains that it requires a middleware function but received undefined.
- Using app instead of router inside a route module. Referencing the global
appfrom within a route file couples that file to the main application and breaks the modularity the router was meant to provide.
- Overlapping mount prefixes. Mounting one router at
/apiand another at/api/userscan cause the broader mount to intercept requests intended for the narrower one, depending on registration order.
- Assuming route parameters are validated. A
:idparameter matches any non-empty segment, includingabcwhen you expected a number. The router captures the string as-is; validation is a separate step you must add.
- Putting a catch-all route above specific routes. A broad pattern such as
/:anythingregistered near the top of a router shadows every route below it, sending all traffic to the catch-all handler.
Best Practices
- Give each resource its own router in its own file. A
routes/users.js, aroutes/orders.js, and so on keepapp.jsa short and readable map of mount points, mirroring one desk per floor.
- Register the most specific routes first. Put literal paths above parameterized ones and narrow patterns above broad ones, so the first-match rule resolves in favor of the specific handler you intended.
- Keep the mount prefix out of the router's own paths. Write routes relative to the mount point and let
app.use('/sales', router)supply the prefix, so the same router could be remounted elsewhere unchanged.
- Use mergeParams when a router needs a parent's parameters. Create nested routers with
express.Router({ mergeParams: true })whenever a child route depends on an id captured by the mount path.
- Attach shared per-router concerns with router.use(). Authentication or logging that applies to one resource belongs as router-level middleware on that router, not scattered across each route or forced onto the whole app.
- Validate route parameters explicitly. Treat
req.paramsvalues as untrusted strings and check their shape before use, since the router itself performs no type or format checking.
- Keep mount prefixes disjoint. Choose non-overlapping prefixes such as
/usersand/ordersso that no request could reasonably match two mounts, removing order sensitivity between routers.
- Export the router as the module's single value. End each route file with
module.exports = routerso consumers import one clear thing and the mounting site reads as a simple table.
Practice Exercises
- Split a monolith into two routers. Take an app with several
/productsand/customersroutes defined directly onappand move them into two router modules mounted at their prefixes. Confirm each URL still responds as before.
- Reproduce and fix the collision. Build a router with
/item/:codeabove a literal/item/new, observe that/item/newis captured by the parameter route, then reorder the routes so/item/newgets its own handler. Explain why the order change fixes it.
- Add scoped authentication. Create an
/adminrouter whoserouter.use()middleware rejects any request lacking anx-adminheader with a 401, and verify that routes mounted outside that router remain open.
- Use a route parameter with validation. Define
/order/:idon a router and add a check that returns 400 whenreq.params.idis not all digits, otherwise echoes the id back. Test it with both a numeric and a non-numeric id.