Skip to main content
Middleware runs before your route handler. Use it for CORS headers, rate limits, logging, timeouts, and auth checks. A MiddlewarePipeline chains middleware together and short-circuits to a Response when one rejects the request. The pipeline works in both router styles. The route module wrapper changes:
  • App router API routes live at app/api/**/route.ts and export named HTTP method handlers such as GET or POST. The handler receives the Request directly.
  • Pages router API routes live at pages/api/** and export named HTTP method handlers or a default fallback handler. The handler receives an APIContext as ctx; use ctx.request when a middleware expects a Request.

Prerequisites

  • At least one API route in your project (see API routes).
  • The dev server running so you can hit the routes with curl.

Built-in middleware

CORS

Rate limiting

Logging

Timeout

Pipeline composition

Combine middleware into a pipeline:

Route-specific middleware

Apply middleware only to matching URL patterns:

Execute the pipeline

The same pipeline can run in a pages router handler by passing ctx.request:
Try it with the dev server running:
The response should include any headers added by the middleware that matched the request. If a middleware returns a Response, the route handler stops there and returns that response.

Cleanup callbacks

Register teardown logic that runs after the response is sent:

Custom middleware

A middleware is a function that receives a context object and a next function. Access the request via c.request:
Add it to a pipeline:

Verify it worked

Hit a route with and without the headers the middleware expects:
For CORS, include an Origin header and confirm Access-Control-Allow-Origin is set on the response.