Middleware

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.

Example

Every API request to your app passes through auth middleware first. The middleware checks if the request includes a valid session token. If yes, the request continues to the handler. If no, the middleware returns a 401 Unauthorized response — the handler never executes.

Middleware handles the repetitive, cross-cutting concerns that every request needs — so your route handlers can focus on business logic.

How Middleware Works

Request → Middleware 1 → Middleware 2 → Middleware 3 → Route Handler → Response
           (auth)        (logging)      (rate limit)    (your code)

Each middleware can:

  • Pass through — Let the request continue
  • Modify — Add data to the request (like the current user)
  • Block — Return an error and stop the chain

Common Middleware Types

MiddlewarePurpose
AuthenticationVerify user identity
AuthorizationCheck user permissions
Rate limitingPrevent API abuse
CORSAllow cross-origin requests
LoggingRecord request details
ValidationCheck request data format

Middleware in Next.js

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.
}

Why Middleware Matters for Vibe Coding

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.

Ad
Favicon