SyntaxStudy
Sign Up
Express.js Express Router for Modular Routes
Express.js Beginner 1 min read

Express Router for Modular Routes

`express.Router()` creates a mini Express application that handles routing independently of the main app. Routers can be mounted at a base path with `app.use()`, enabling you to split route definitions across multiple files without repeating the base path in every route. Each Router instance supports the same middleware API as the main app, so you can attach router-level middleware that only applies to routes within that file. This is the standard pattern for feature-based code organisation in production Express applications. Nested routers are also possible: a `/api` router can itself mount a `/users` sub-router and a `/posts` sub-router, creating a clean hierarchy that mirrors the URL structure. Combining `Router` with controller files keeps each layer focused on a single responsibility.
Example
// routes/users.js
const express    = require('express');
const router     = express.Router();
const controller = require('../controllers/userController');
const auth       = require('../middleware/auth');

// All routes below inherit the /users prefix from app.use()

router.get('/',     controller.list);
router.get('/:id',  controller.show);
router.post('/',    auth, controller.create);
router.put('/:id',  auth, controller.update);
router.delete('/:id', auth, controller.destroy);

module.exports = router;

// ─────────────────────────────────────────────────────────────
// routes/index.js
const express   = require('express');
const router    = express.Router();
const userRoutes = require('./users');
const postRoutes = require('./posts');

router.use('/users', userRoutes);
router.use('/posts', postRoutes);

module.exports = router;

// ─────────────────────────────────────────────────────────────
// app.js  (mounting)
const app    = require('express')();
const routes = require('./routes');
app.use(require('express').json());
app.use('/api/v1', routes);
app.listen(3000);