Routing and middleware
The real power of Express is middleware: small functions that every request flows through on its way to your route. Logging, parsing bodies, checking logins, adding security headers and handling errors are all middleware.
What middleware is
A middleware function receives req, res and next. It can read or change the request, send a response itself, or call next() to pass control to the next function in line:
request → [logger] → [express.json] → [auth check] → [route handler] → responseIf a middleware neither sends a response nor calls next(), the request hangs forever. Every middleware must do one or the other.
Middleware for some routes only
Middleware can be attached to a path prefix or to individual routes:
Routers: organising a bigger app
As an app grows, put related routes in an express.Router() in its own file, and mount it under a prefix:
A common project layout:
src/
├── app.js creates the app, adds middleware, mounts routers
├── server.js imports app and calls app.listen()
├── routes/ one router per resource (users.js, orders.js)
├── middleware/ auth.js, errors.js, validate.js
└── services/ business logic and database accessKeeping app (configuration) separate from server (listening) makes the app easy to test, as you'll see in the testing lesson.
Error handling
Middleware with four parameters, (err, req, res, next), is an error handler. Express sends errors to it when a route throws or calls next(err):
- Express 5 catches errors in
asynchandlers automatically: a rejected promise goes to your error handler. (In Express 4 you had to wrap async handlers or callnext(err)yourself.) - Never send internal details (stack traces, SQL errors) to clients. Log them on the server, and send a generic message.
- Put the 404 handler and the error handler after all routes.
Popular middleware packages
| Package | Purpose |
|---|---|
helmet |
Sets security headers (and removes X-Powered-By) |
cors |
Allows browsers on other domains to call your API |
morgan |
Logs each request |
cookie-parser |
Parses cookies into req.cookies |
express-rate-limit |
Limits requests per client to stop abuse |
compression |
Gzips responses |
Practice
- Write a
timingmiddleware that adds anX-Response-Timeheader with the time the request took. - Create a
productsrouter withGET /andGET /:idand mount it at/api/products. - Make the error handler return
{ "error": …, "path": … }and log 500 errors with the request method and URL.
1.What must a middleware function do if it doesn't send a response?
2.How does Express recognise an error-handling middleware?
3.In Express 5, what happens when an async route handler throws?