What Is Middleware?
Middleware is code that runs between receiving a request and sending a response, forming a processing pipeline. Each middleware function can inspect, modify, or reject the request before passing it to the next middleware or the final handler. Used in Express, Django, Next.js, and most web frameworks.
How Middleware Works
Express middleware chain: Request → Logger (logs method + URL) → Auth (validates JWT, rejects if invalid) → RateLimiter (checks request count) → CORS (adds headers) → Route Handler → Response. Each middleware calls next() to pass control to the next one. If auth fails, it sends 401 without reaching the handler.
Key Concepts
- Pipeline — Request flows through a chain of middleware functions — each can process, modify, or short-circuit
- next() Function — Calls the next middleware in the chain — if not called, the request stops at this middleware
- Error Middleware — Special middleware that handles errors — receives (err, req, res, next) instead of (req, res, next)
Frequently Asked Questions
What are common middleware use cases?
Authentication, logging, CORS headers, rate limiting, request parsing, compression, error handling, and input validation.