Node.js › Express & Middleware
How would you structure a large Express application using the Router to organize routes into feature-based or resource-based modules?
AdvancedAnswer
Rather than defining every route directly on the main app object in one large file, express.Router() lets related routes be grouped into their own module (users.js, orders.js, each exporting a configured Router instance), which the main application file then mounts at an appropriate base path -- this keeps each feature's routing, middleware, and validation logic self-contained and makes a growing application's route structure much easier to navigate and maintain.
// routes/users.js
const router = express.Router();
router.get('/', listUsers);
router.get('/:id', getUser);
router.post('/', createUser);
module.exports = router;
// app.js
app.use('/api/users', require('./routes/users'));
app.use('/api/orders', require('./routes/orders'));Real-world example A growing e-commerce API splits its routes into separate users.js, orders.js, and products.js router modules, each mounted at its own base path in the main app file, replacing what had become an unwieldy 2,000-line single routes file with a clean, feature-organized structure.