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.tsand export named HTTP method handlers such asGETorPOST. The handler receives theRequestdirectly. - Pages router API routes live at
pages/api/**and export named HTTP method handlers or adefaultfallback handler. The handler receives anAPIContextasctx; usectx.requestwhen a middleware expects aRequest.
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
ctx.request:
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 anext function. Access the request via c.request:
Verify it worked
Hit a route with and without the headers the middleware expects:Origin header and confirm
Access-Control-Allow-Origin is set on the response.