Express express.Router()
What you’ll learn
- How to create routers with
express.Router(). - How to use router options like
mergeParams. - How to attach router-specific middleware.
- How to mount routers cleanly in the main app.
Syntax
javascript
const router = express.Router([options]);1
Create a basic router
javascript
const express = require('express');
const router = express.Router();
router.get('/', function (req, res) {
res.send('Router home');
});2
Router with mergeParams
javascript
const childRouter = express.Router({ mergeParams: true });
childRouter.get('/', function (req, res) {
res.json({ teamId: req.params.teamId });
});❓ FAQ
It returns a new router instance you can use to define middleware and routes for a specific module.
mergeParams allows child routers to access params defined in parent route paths.
Yes. router.use() applies middleware to routes within that router.
app is the top-level application object; Router is a modular subset used for route grouping.
Use options when you need custom behavior like strict routing, case sensitivity, or parent param access.
Did you know?
express.Router([options]) creates isolated mini-routing stacks with configurable behavior like mergeParams.
4 people found this page helpful
