Express router Object
What you’ll learn
- What an Express router object is and why it is useful.
- How to define routes and middleware in a router module.
- How to mount routers and compose larger applications.
- How to avoid router scope and ordering pitfalls.
Syntax
javascript
var express = require('express');
var router = express.Router();1
Create and export a router module
javascript
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.send('Users home');
});
module.exports = router;2
Mount router on app
javascript
var userRouter = require('./routes/users');
app.use('/users', userRouter);
// '/users' prefix is applied to all userRouter routes⚠️ Common pitfalls
- Mounting router at wrong prefix and creating broken endpoint paths.
- Adding middleware after handlers that depend on it.
- Keeping too many unrelated routes in one router file.
❓ FAQ
It is an instance created by express.Router() that holds middleware and route handlers.
They help organize routes by feature and keep applications modular.
Mount it using app.use('/prefix', router).
Yes. Use router.use() to attach middleware scoped to that router.
Yes. You can mount child routers within parent routers for hierarchical modules.
Did you know?
An Express router instance works like a mini app with its own middleware stack and route handlers.
4 people found this page helpful
