← Node.js & Express learning pathNode.js & Express · Module 7 of 10
Middleware
Run shared code for every request: logging, parsing, auth and errors.
📖 Key ideas
- Middleware is (req, res, next) => { ... }.
- Call next() to pass control on.
- app.use registers middleware for all routes.
- Popular: cors, helmet, morgan, express-rate-limit.
- Error middleware has four args: (err, req, res, next).
💡 Real-life example: Middleware is airport security: each checkpoint inspects you and lets you through (next) or stops you.
next()Passes to the next middleware
corsAllows cross-origin requests
helmetSets security headers
Error middlewareHandler with (err, req, res, next)