Middleware
Middleware is a function (or class) that sits in the request-handling pipeline of a web framework, intercepting requests before they reach the handler and responses before they leave the server. Middleware is how cross-cutting concerns (logging, auth, parsing, CORS, rate limiting, compression) are composed without touching each route.
The pattern
A middleware receives the request, the response, and a "next" callable. It can:
- Inspect or modify the request
- Short-circuit by returning a response without calling next
- Call next to pass control downstream
- Inspect or modify the response after downstream has run
Middlewares compose like an onion: each one wraps the next. The order matters: auth before route handling, logging at the outermost layer, error handling at the right spot to catch downstream throws.
Common middleware categories
- Parsing: JSON body, URL-encoded body, multipart form, cookies
- Security: CORS, CSRF, helmet (security headers), rate limiting
- Auth: JWT validation, session loading, OAuth callbacks
- Observability: request logging, tracing, metrics, request ID propagation
- Compression and caching: gzip, brotli, ETag, conditional GET
Same pattern in other ecosystems
- Django:
MIDDLEWAREsetting; class-based callables - Rails: Rack middleware
- ASP.NET:
app.Use(...)in the request pipeline - Java: Servlet filters; Spring interceptors
- Go: function chains taking
http.Handler
🔗