tezvyn:

Modularize routes with express.Router

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

structuring a growing app.

OUTLINE

create a Router per resource in its own file, define routes on it, export it, and mount with app.use('/products', router).

WHAT THIS TESTS This evaluates whether you can decompose a monolithic route file into maintainable, resource-scoped modules using Express's Router.

A GOOD ANSWER COVERS The idiomatic approach is to create an express.Router() instance for each resource, in its own file such as routes/products.js. You define the routes on that router relative to the mount point, using router.get('/'), router.get('/:id'), router.post('/'), and so on, where '/' corresponds to the collection. You export the router and, in the main app file, mount it once with app.use('/products', productsRouter). Express prefixes every route on that router with /products, so you write paths relative to the resource and avoid repeating the prefix. This keeps the entry file thin, colocates a resource's handlers, and lets you attach resource-specific middleware via router.use().

COMMON WRONG ANSWERS Keeping all routes in the main file. Repeating the /products prefix on each route inside the router, producing /products/products. Calling express() again instead of express.Router() in submodules. Forgetting to export or mount the router. Mounting the same router at two paths and being surprised by shared middleware.

LIKELY FOLLOW-UPS How do route paths combine with the mount path? Where would you put controllers versus routers? How do you add validation middleware per router? How does this scale to dozens of resources?

ONE CONCRETE EXAMPLE In routes/products.js: const router = require('express').Router(); router.get('/', listProducts); router.get('/:id', getProduct); router.post('/', createProduct); module.exports = router; In app.js: app.use('/products', require('./routes/products')); Now GET /products hits listProducts and GET /products/42 hits getProduct, while the main file stays a short list of mounts instead of hundreds of route lines.

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.