Q8: What is `express.Router()` and why is it useful?
express.Router() creates an isolated instance of middleware and routes. It acts as a 'mini-app' capable only of performing middleware and routing functions.
Benefits
- Modularizes complex applications into sub-modules.
- Groups related routes (e.g.,
/api/v1/users,/api/v1/orders) into separate files. - Encapsulates route-specific middleware rules.
Modular Routing with Express Router
// routes/userRoutes.js
const express = require('express');
const router = express.Router();
router.get('/profile', (req, res) => res.json({ user: 'John' }));
module.exports = router;
// server.js
const userRoutes = require('./routes/userRoutes');
app.use('/users', userRoutes); // Mounts on /users/profile💡 Router instances are exported and mounted cleanly on main application prefixes.
Key Takeaways
- Routers allow modular separation of endpoints by domain logic.
- Routes defined on routers inherit the path prefix where the router is mounted.