Modular route organization
Split a large application into independently maintained endpoint groups.
Express.js · Function
express.Router([options]) creates a modular router that combines middleware and HTTP-method routes. Configure case sensitivity, parent-parameter inheritance, or strict trailing-slash matching with the optional options object.
express.Router([options]) creates a reusable router object that combines middleware and route handlers. Configure matching behavior when needed, add routes with methods such as get or post, and mount the router with app.use() or another router's use() method.
express.Router([options])| Name | Type | Description |
|---|---|---|
options | Object | Optional configuration object. caseSensitive defaults to false; mergeParams defaults to false; strict defaults to false. |
Router object
express.Router() produces a new router instance.mergeParams lets a nested router retain parameters supplied by its parent.caseSensitive: true when route paths must distinguish letter case.strict: true when trailing slashes should affect route matching.caseSensitive is enabled.strict routing is enabled.mergeParams, child parameters override parent parameters when their names collide.const express = require('express');
const app = express();
const users = express.Router();
users.get('/:id', (req, res) => {
res.json({ id: req.params.id });
});
app.use('/users', users);
app.listen(3000);Creates a router for user endpoints and mounts it under /users, so the route responds at /users/:id.
Split a large application into independently maintained endpoint groups.
Attach authentication, logging, or validation only to a group of routes.
Reuse a route module beneath different application mount paths.
express.Router() create, and how is it used?express.Router() returns a router object that acts as middleware and a routing system. It can be passed to app.use() or another router's use() method, then configured with middleware and HTTP-method routes.
Follow-up: How would you preserve parameters captured by a parent router? Pass { mergeParams: true } when creating the child router.
caseSensitive?The caseSensitive option controls whether route matching distinguishes uppercase and lowercase paths. Its default is false, so paths such as /Foo and /foo match equivalently.
Follow-up: How do you make /Foo and /foo distinct? Create the router with { caseSensitive: true }.
strict option change?The strict option controls trailing-slash matching. It defaults to false, making /foo and /foo/ equivalent for that router.
Follow-up: How do you require the slash form to matter? Create the router with { strict: true }.
app.use()router.use()router.METHOD()router.route()req.params