CodePark/ questions / HTTP servers & Express middleware
START PRACTICINGPRACTICE
Backend question · Node.js › HTTP servers & Express middleware

What is middleware in Express, and what does next() do?

Middleware is a function (req, res, next) that runs as one step in the handling of a request. Express keeps an ordered list (a stack) of middleware and route handlers. Each request goes through the matching ones, in the order you registered them.

A middleware can do one of these things:

  • Read or change req and res.
  • End the request by sending a response.
  • Call next() to pass control to the next matching function.

If it neither sends a response nor calls next(), the request hangs until the client times out.

next(err) with an argument skips all the remaining normal middleware. Express jumps straight to the error-handling middleware.

Typical middleware:

  • Body parsing with express.json()
  • Logging
  • Authentication
  • CORS
  • Rate limiting

Registration order matters. For example, a body parser must come before the routes that read req.body, because otherwise req.body is not filled yet.

  • Middleware has the signature (req, res, next) and runs in registration order.
  • It can change req/res, end the response, or call next().
  • If it does neither, the request hangs.
  • next(err) jumps to the error handlers.
  • Order matters: for example, the body parser must come before the routes.