Modular route organization
Group endpoints for a feature or resource in a dedicated module.
Express.js · Class
express.Router() creates a modular, mountable router that combines middleware and route handlers. Add routes to it and mount it with app.use() or another router.
express.Router() creates a self-contained routing and middleware object. Define middleware and HTTP-method handlers on it, then mount it with app.use() so its paths are resolved relative to the mount point.
express.Router([options])| Name | Type | Description |
|---|---|---|
options | Object | Options object controlling router behavior, including caseSensitive, mergeParams, and strict. |
A new Router object.
app.use() to integrate its middleware and routes into the application pipeline.express.Router() to construct a new router.get, post, and put for method-specific routing.next('router') when a condition should leave the current router and return control to the outer middleware chain.next('route') skips the remaining callbacks for that route.const express = require('express');
const app = express();
const router = express.Router({ mergeParams: true });
router.use((req, res, next) => {
res.locals.source = 'calendar';
next();
});
router.get('/events', (req, res) => {
res.json({ calendarId: req.params.calendarId, source: res.locals.source });
});
app.use('/calendars/:calendarId', router);
app.listen(3000);Creates a mountable router, adds router-level middleware and a GET route, then mounts it beneath a parameterized application path.
Group endpoints for a feature or resource in a dedicated module.
Attach authentication, logging, or other middleware only to one route group.
Reuse the same route bundle beneath different application mount paths.
express.Router() returns a router object that combines middleware and routing behavior. It can be passed to app.use() or mounted on another router, making it suitable for modular route groups.
Follow-up: How does mounting affect a route path? A route such as /events on a router mounted at /calendar is reached through the combined path /calendar/events.
mergeParams option do?mergeParams preserves parameter values from the parent router; its default is false. If parent and child routers use the same parameter name, the child value wins.
Follow-up: When should it be enabled? Enable it when handlers in the child need parameters captured by the parent mount path.
router.METHOD() methods, such as router.get() and router.post(), define handlers for particular HTTP methods. router.route(path) returns a single route object that can then receive multiple HTTP-verb handlers.
Follow-up: How can middleware be applied across methods? Use router.use() for router-level middleware, or pass middleware callbacks to a method-specific route.
express()router.use()router.METHOD()router.route()app.use()