Middleware
Run code before and after your API handlers
What is Middleware?
Middleware runs before your API handler. Use it for authentication, logging, error handling, or any logic that applies to multiple endpoints.
How It Works
A middleware is a function that receives three arguments:
- req - The incoming request (same as handler)
- ctx - The context object (same as handler)
- next() - Call this to continue to the handler
If you don't call next(), the request stops. The handler never runs.
Simple Example
Execution Order
Middleware runs in the order you list them:
Modifying Responses
Await next() to get the response, then modify it:
Passing Data to Handlers
Middleware can attach data to the req object, making it available to your handler. This is perfect for authentication—verify the user once in middleware, then use their details in the handler.
First, extend the request type in api.d.ts:
Then attach the data in your middleware:
Now use it in your handler:
Learn more: Check out the Middleware Auth Handler Example to see a complete project with JWT validation and type safety.
Error Handling
Catch errors from handlers:
Reusing Middleware
Create middleware files in a shared location:
Import and use across steps: