Middleware is code that runs between a request arriving and your application handling it. It intercepts every request to perform common tasks like authentication checks, logging, rate limiting, and CORS handling — before the actual route handler runs. Think of it as a security checkpoint before entering a building.
Middleware handles the repetitive, cross-cutting concerns that every request needs — so your route handlers can focus on business logic.
Request → Middleware 1 → Middleware 2 → Middleware 3 → Route Handler → Response
(auth) (logging) (rate limit) (your code)
Each middleware can:
| Middleware | Purpose |
|---|---|
| Authentication | Verify user identity |
| Authorization | Check user permissions |
| Rate limiting | Prevent API abuse |
| CORS | Allow cross-origin requests |
| Logging | Record request details |
| Validation | Check request data format |
Next.js has a special middleware.ts file at the project root:
export function middleware(request) {
// Runs before every matching route
// Check auth, redirect, modify headers, etc.
}
Without middleware, you'd repeat the same checks in every API route. With middleware, you write the logic once and it applies everywhere. When asking AI to add features like authentication or rate limiting, it typically implements them as middleware — the right pattern for the job.