Express router.route() Method
What you’ll learn
- How to group GET/POST/PUT/DELETE handlers for one router path.
- How chaining reduces path repetition and improves readability.
- How to attach middleware in chained methods.
- How to avoid large, hard-to-maintain route chains.
Syntax
javascript
router.route(path)
.get(handler)
.post(handler)
.put(handler)
.delete(handler);1
Basic chained router handlers
javascript
router.route('/users/:id')
.get(function (req, res) {
res.send('Get user');
})
.put(function (req, res) {
res.send('Update user');
})
.delete(function (req, res) {
res.send('Delete user');
});2
Chain methods with middleware
javascript
function auth(req, res, next) {
if (!req.user) return res.status(401).send('Unauthorized');
next();
}
router.route('/orders')
.get(auth, function (req, res) {
res.send('List orders');
})
.post(auth, function (req, res) {
res.status(201).send('Create order');
});3
Final path after mounting router
javascript
app.use('/api', router);
// router.route('/products') becomes '/api/products'⚠️ Common pitfalls
- Creating overly long chains that reduce readability.
- Using wrong HTTP methods for operation semantics.
- Forgetting that mounted prefixes are part of the final route URL.
❓ FAQ
It creates a route object for one path and lets you chain method handlers on a router instance.
Use it when the same router path has multiple HTTP methods and you want cleaner grouped definitions.
They are conceptually the same, but router.route() is used inside express.Router() modules.
Yes. Each chained method can include middleware before the final handler.
No. It mainly improves organization while keeping standard Express matching rules.
Did you know?
router.route(path) returns a route instance so you can chain handlers like .get(), .post(), and .delete() in one grouped block.
4 people found this page helpful
