← Node.js & Express learning path
Node.js & Express · Module 7 of 10

Middleware

Run shared code for every request: logging, parsing, auth and errors.

📖 Key ideas

  1. Middleware is (req, res, next) => { ... }.
  2. Call next() to pass control on.
  3. app.use registers middleware for all routes.
  4. Popular: cors, helmet, morgan, express-rate-limit.
  5. 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)