express.Router

Group related routes into a mini-app with express.Router and mount it under a path.

Syntaxconst router = express.Router();

As an app grows, keeping every route in one file becomes messy. express.Router lets you build a group of routes in its own module, then mount the whole group under a base path with app.use().

Below, a router handles all /users routes. Mounting it at /users means its / becomes /users and its /:id becomes /users/:id.

An Express Router mounted under a base pathapp.use('/users', router)usersRouterrouter.get('/') => GET /usersrouter.get('/:id') => GET /users/:idrouter.post('/') => POST /users
A router bundles related routes; mounting adds the base path to each.

Example

Example · javascript
// routes/users.js
const express = require('express');
const router = express.Router();

router.get('/', (req, res) => res.send('All users'));
router.get('/:id', (req, res) => res.send('User ' + req.params.id));
router.post('/', (req, res) => res.send('Create user'));

module.exports = router;

// app.js
const usersRouter = require('./routes/users');
app.use('/users', usersRouter);

When to use it

  • A large API extracts all /users routes into a usersRouter module, keeping the main app.js clean and focused on mounting routers.
  • A developer creates a separate adminRouter with its own middleware chain that adds role-checking before every admin route.
  • A team splits the codebase into feature folders, each exporting its own express.Router() for the main app to mount.

More examples

Creating and mounting a router

Defines a Router in its own module and mounts it under /users, so router.get('/') maps to GET /users.

Example · js
// routes/users.js
const router = require('express').Router();

router.get('/', (req, res) => res.json([]));
router.post('/', (req, res) => res.status(201).json({ created: true }));

module.exports = router;

// app.js
const usersRouter = require('./routes/users');
app.use('/users', usersRouter);

Router-level middleware

Uses router.use() to register middleware that runs for every route inside this specific router.

Example · js
const router = require('express').Router();

// Middleware applied to every route in this router
router.use((req, res, next) => {
  console.log('Users router hit:', req.method, req.url);
  next();
});

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

module.exports = router;

Nested routers

Mounts two separate routers under /api/v1 and /api/v2 to version an API without duplicating the main app.

Example · js
const express = require('express');
const v1 = express.Router();
const v2 = express.Router();

v1.get('/status', (req, res) => res.json({ version: 1 }));
v2.get('/status', (req, res) => res.json({ version: 2 }));

const app = express();
app.use('/api/v1', v1);
app.use('/api/v2', v2);
app.listen(3000);

Discussion

  • Be the first to comment on this lesson.