What Is Middleware in Web Development?

Middleware is code that runs between receiving a request and producing a response, able to inspect, modify, or reject the request/response, or pass it along...

Published October 7, 2026

Middleware is code that sits between the incoming request and your route handler (and often the response), performing cross-cutting tasks such as logging, authentication, CORS and parsing. Each piece can pass the request on or stop it.

The concept

Requests flow through a chain: middleware 1 → middleware 2 → handler, then back out. Each middleware can modify the request, short-circuit with a response, or call next().

Order matters: authentication must run before authorisation, and body parsers before handlers that read the body.

The chain

next()next()LoggermiddlewareAuthmiddlewareHandlerroute
Each layer can pass on or stop the request.

Practical examples

Express

app.use((req, res, next) => { console.log(req.method, req.url); next() })
app.use(requireAuth)
app.get('/me', (req, res) => res.json(req.user))

Laravel

Route::middleware('auth:sanctum')->get('/me', fn () => auth()->user());

Short-circuit

function requireAuth(req, res, next) {
  if (!req.user) return res.sendStatus(401)
  next()
}

Common mistakes

  • Forgetting to call next(), leaving requests hanging.
  • Wrong middleware order.
  • Putting business logic in middleware.

Key takeaways

  • Middleware wraps requests in a chain.
  • Call next() or respond, never neither.
  • Order is significant.

FAQ

Can middleware modify responses?

Yes, by acting after next() or wrapping the response methods.

Global vs route middleware?

Global runs for all requests, route middleware only where attached.

More General articles