intermediate

Express routing

Design route trees with method matching, path parameters, router mounting, handler composition, and clear resource boundaries.

Express maps HTTP methods and path patterns to handler functions. Routes can be declared on the app or on `express.Router()` instances mounted at prefixes — this keeps resource boundaries clear and enables modular route trees.

					const users = express.Router({ mergeParams: true });
users.get('/:id', getUser);
users.post('/', createUser);
app.use('/api/users', users);
				

Path params (`:id`), optional params, and regex segments capture URL data. `mergeParams: true` lets nested routers see parent params. Method-specific handlers (`app.get`, `app.post`) run only for matching verbs; `app.all` matches every method.

On interviews: explain route registration order (first match wins), mounting routers for feature modules, and why handlers should stay thin — validation and domain logic belong in middleware or services.

Common pitfalls: overlapping routes where a broad pattern shadows a specific one, forgetting `mergeParams` in nested routers, and putting business logic directly in route callbacks.

The trade-off is balancing simplicity, performance, safety, and operability — name which axis you optimized and what cost you accepted.

Checklist:

  • Group routes by resource with Router mounting.
  • Keep handlers thin; delegate to services.
  • Name params consistently across nested routers.
  • Document which routes are public versus protected.