Modularizing routes with express.Router
structuring a growing app.
create a Router instance in users.js, attach routes to it, export it, then mount it under a base path with app.use in the main file.
duplicating the base path on every route instead of mounting.
WHAT THIS TESTS This evaluates your ability to structure a real application as it grows beyond a single file, and your grasp of Express's composable routing.
A GOOD ANSWER COVERS express.Router creates a modular, mountable mini-application that has its own routes and middleware but no server of its own. In users.js you call express.Router to create a router instance, define your endpoints on it relative to a base path, for example router.get('/') and router.get('/:id'), and export the router. In the main application file you import it and mount it with app.use('/users', usersRouter). Express then prefixes every route in the router with /users, so router.get('/') answers /users and router.get('/:id') answers /users/42. This keeps each feature's routes in its own file, lets you attach middleware that applies only to that router, and makes the main file a thin assembly of mounted routers. The pattern scales cleanly as you add more feature areas.
COMMON WRONG ANSWERS Writing full paths like router.get('/users/:id') inside the file and also mounting under /users, producing /users/users/:id. Importing the router but forgetting to app.use it. Confusing a Router with a full app instance.
LIKELY FOLLOW-UPS How do you apply middleware to only one router. How do nested routers and mergeParams work. How would you organize controllers separately from routers.
ONE CONCRETE EXAMPLE In users.js: const router = express.Router(); router.get('/', listUsers); router.get('/:id', getUser); module.exports = router;. In app.js: app.use('/users', require('./users'));. Now GET /users runs listUsers and GET /users/42 runs getUser with req.params.id equal to '42', while the main file stays short and each feature lives in its own module.
Read the original → expressjs.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.