Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 43 ยท Routing

Modular Routing with express.Router

Split an Express app into small routers: mount them under a prefix, share parameters with mergeParams, add router-level middleware and chain verbs with app.route.

A tiny app can keep every route in one file. A real one cannot: after thirty routes you are scrolling, after a hundred you are afraid to touch anything. express.Router() solves this by letting you build a mini application that only holds routes, and then plug it into the main app under a URL prefix.

A router is not a second server. It is a function with the same use, get, post and friends as app, and you hand it to app.use(prefix, router). Everything you learned in Routing Basics and Route Parameters works inside it unchanged.

Your first router

Real Express code is read-only on this site. Here is a router for users, in its own file:

JavaScript
// routes/users.js
import { Router } from 'express';

const router = Router();

router.get('/', (req, res) => {
  res.json([{ id: 1, name: 'Ada' }, { id: 2, name: 'Linus' }]);
});

router.get('/:id', (req, res) => {
  res.json({ id: req.params.id });
});

export default router;

And the main app that mounts it:

JavaScript
// app.js
import express from 'express';
import usersRouter from './routes/users.js';

const app = express();
app.use('/users', usersRouter);

app.listen(3000);

Notice that the router writes '/' and '/:id', not '/users' and '/users/:id'. The prefix is supplied by whoever mounts the router. That makes the router reusable: you can mount the same one at /users and at /api/v1/users without editing it.

Why use routers?

Organize One file per resource.
Reuse Mount the same router under several prefixes.
Test Exercise one area without the rest of the app.

A router is a mini app made only of routes and middleware.

1 / 2

How mounting works

When a request for GET /users/42 arrives, the app checks its layers in order. The layer created by app.use('/users', usersRouter) matches because the path starts with /users. Express then does something important: it removes the matched prefix and calls the router with the remainder, /42. The router matches /:id against that remainder.

Three properties show the split:

  • req.baseUrl is the part that was matched and removed (/users).
  • req.path is what is left for the router to match (/42).
  • req.originalUrl always keeps the full original URL (/users/42).
flowchart LR
  A["GET /users/42"] --> B["app.use('/users', router)"]
  B -->|"strip /users"| C["router sees /42"]
  C --> D["router.get('/:id')"]
  D --> E["res.json(...)"]

The app strips the mount prefix before the router matches its own paths.

The stand-in below does the same stripping. Its framework block is long, but you can skip to the lines after stand-in framework: end, which are the lesson itself.

Node.js Mounting a router under a prefix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last request matches the /users prefix, but no route inside the router matches /42/extra, so the walk continues out of the router and the app answers 404.

Router-level middleware

Middleware attached to a router only runs for requests that reach that router. This is the cleanest way to protect one area of an app:

JavaScript
const admin = Router();

admin.use((req, res, next) => {
  if (req.get('x-admin-key') !== process.env.ADMIN_KEY) {
    return res.status(403).json({ error: 'Admins only' });
  }
  next();
});

admin.get('/stats', (req, res) => res.json({ users: 10 }));

app.use('/admin', admin);

Requests to / or /users never touch that check, while every request under /admin does. The next chapter explains how middleware works in depth.

You can also pass middleware to a single route, or only to the mount:

JavaScript
app.use('/orders', requireLogin, ordersRouter);
router.post('/', validateOrder, createOrder);

Parameters and mergeParams

A mount path can contain parameters too, for example app.use('/users/:userId/posts', postsRouter). By default the router does not see userId. Each router starts with its own empty req.params. To receive the parent's parameters, create the router with mergeParams: true:

JavaScript
const posts = Router({ mergeParams: true });

posts.get('/:postId', (req, res) => {
  // both parameters are available
  res.json({ user: req.params.userId, post: req.params.postId });
});

app.use('/users/:userId/posts', posts);

Forgetting mergeParams is the classic bug here: req.params.userId is simply undefined, and no error tells you why.

Node.js mergeParams on or off

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first response contains only postId; the second contains both. Real Express behaves the same way.

Chaining verbs with route()

Often one path has several verbs. Instead of repeating the path, route() returns an object you chain:

JavaScript
router
  .route('/:id')
  .get((req, res) => res.json({ id: req.params.id }))
  .put((req, res) => res.json({ updated: req.params.id }))
  .delete((req, res) => res.status(204).end());

This avoids typos in the repeated path and groups a resource's behavior in one place. It is purely a convenience: it registers exactly the same routes as three separate calls.

Node.js One path, several verbs with route()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The PATCH call has no matching route here, so it falls through to the 404 fallback. (Real Express also answers 404 by default; it only auto-answers OPTIONS and HEAD.)

router.param(): load a resource once

Many routes share the same parameter. GET /users/:id, PUT /users/:id, DELETE /users/:id and GET /users/:id/posts all start by finding user :id and answering 404 if there is none. Repeating that code in four handlers is tedious and easy to get wrong. router.param(name, callback) runs a callback whenever a route containing :name matches, before the route handlers:

JavaScript
// Real Express
router.param('id', async (req, res, next, value, name) => {
  const user = await db.findUser(value);        // value is the text of :id
  if (!user) return res.status(404).json({ error: `No user with ${name} ${value}` });
  req.user = user;                              // preload for the handlers
  next();
});

router.get('/:id', (req, res) => res.json(req.user));        // no lookup code here
router.put('/:id', (req, res) => res.json({ ...req.user, ...req.body }));
router.get('/:id/posts', (req, res) => res.json(posts.for(req.user)));

The callback receives the usual req, res, next, plus the value of the parameter and its name. Rules worth remembering:

  • It is called once per request, even if several routes in the chain match the same parameter value.
  • It is local to the router where you define it. It does not run for parameters of routes in a different router (including routers mounted below), which keeps routers independent.
  • It runs after any middleware that matches earlier and before the route handler. Calling next(err) (or throwing, in an async callback with Express 5) goes to the error handler.
  • It only fires for parameters in route paths of that router, not for parameters in the mount path (app.use('/users/:id', router) uses mergeParams, described above).

Use it for loading by id, validating a format (/^\d+$/) and normalizing values. Keep it light: heavy logic belongs in a service (Controllers and Services).

router.all() and use() versus get()

Three registration methods look alike but match differently:

Method Matches Path rule req.url inside
router.use('/api', fn) every HTTP method The path is a prefix: /api, /api/x, /api/x/y The prefix is stripped (/x/y)
router.all('/api', fn) every HTTP method Exact path (with route-style params) Unchanged
router.get('/api', fn) GET only (and HEAD) Exact path Unchanged

all() is perfect for logic that applies to every verb of one route, such as "require login for this path" or a quick 405 Method Not Allowed fallback. use() is for middleware and for mounting routers, because the prefix stripping is what makes a mounted router think it lives at /. route(path) (from the previous section) is not a different matching rule; it is a bundle that shares one path between several verbs, and it can include .all() as well.

Seeing param callbacks, all() and use() work

The stand-in router below implements param, all, use and route. It prints which callbacks ran for each request so you can check the "once per request" rule and compare use with get.

Node.js router.param, router.all, use() vs get()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check the log lines. param id=1 appears once for /users/1, even though both all and get match that path; the all callback and then the get handler follow, and req.user was already loaded. /users/1/posts reuses the same param callback for a different route. For /users/99 the param callback answered 404, so none of the handlers ran. use('/files', ...) matched /files/img/logo.png and saw req.url as /img/logo.png (prefix stripped), while get('/exact') refused /exact/extra because get needs an exact path.

In Express 5, an async param callback that throws or rejects is forwarded to your error handler automatically, as for any handler. In Express 4 you must catch errors and call next(err) yourself. The older form app.param(callbackFunction) (a function with no name) was removed; always pass a parameter name.

Structuring a real project

A common layout gives each resource its own router file and one place that mounts them all:

JavaScript
// routes/index.js
import { Router } from 'express';
import users from './users.js';
import posts from './posts.js';

const api = Router();
api.use('/users', users);
api.use('/posts', posts);

export default api;

// app.js
app.use('/api/v1', api);

Routers nest as deeply as you like, which is how versioned APIs are built. Keep the handler bodies thin and move real work into controllers and services; Controllers and Services shows how. Remember that order still matters: a router mounted earlier gets the first chance to answer, and a catch-all 404 belongs after every mount.

Do not mount a router at a path that already has a more specific handler registered after it, and do not call next() after sending a response. Both lead to confusing double handling.

What is real and what is the stand-in

The Router() function, mergeParams, req.baseUrl, route() and prefix mounting in the real-code blocks are real Express 5. The runnable examples use our own stand-in, which supports only :name segments and fixes the details that do not matter here (it has no req.originalUrl, no case-insensitive matching and no strict option). Real Express routers also accept options such as caseSensitive and strict.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. You mount a router with app.use('/users', router). Which path should the router use for the list of users?

    Express strips the mount prefix, so the router sees the remaining path. The list lives at the router's "/".
  2. 2. A router is mounted at '/teams/:teamId/members' and its handler reads req.params.teamId, which is undefined. What is the most likely fix?

    By default a router does not inherit parameters from its mount path. mergeParams true copies them in.
  3. 3. What does req.baseUrl contain inside a router mounted at '/users' for the request GET /users/42?

    baseUrl is the matched mount prefix. req.path holds the remainder, "/42".
  4. 4. What does router.route('/:id').get(a).put(b) do?

    route() returns a chainable object that attaches verbs to one path, avoiding repeated path strings.

Summary

  • express.Router() creates a mini app that holds routes and middleware.
  • Mount it with app.use(prefix, router); inside, write paths relative to the prefix.
  • req.baseUrl is the matched prefix and req.path is the remainder.
  • Middleware on a router only runs for requests that reach it.
  • Use Router({ mergeParams: true }) to read parameters from the mount path.
  • route(path) chains several verbs on one path.

Next: How Middleware Works.