Basic Middleware Structure
A middleware is a function that receives the context object and anext() function:
The Context Object
The context object (c) provides access to the request and response:
Calling next()
Thenext() function passes control to the next middleware or route handler. Always await it:
Common Middleware Patterns
Before/After Pattern
Execute code before and after the route handler:Early Return Pattern
Return a response without callingnext():
Modifying Request Data
Add data to the context for later use:Modifying Response
Change the response after the handler:Parameterized Middleware
Create middleware that accepts options:Error Handling
Handle errors in middleware:Async Operations
Perform async operations in middleware:TypeScript Types
Properly type your middleware for better type safety:Factory Pattern
Create a reusable middleware factory:Testing Middleware
Test your custom middleware:Best Practices
Always await next()
Always await next()
Failing to await
next() can cause unexpected behavior and broken error handling:Don't modify the context object directly
Don't modify the context object directly
Use
c.set() to store values instead of adding properties:Handle errors properly
Handle errors properly
Wrap risky operations in try-catch blocks:
Use TypeScript for better type safety
Use TypeScript for better type safety
Define your environment types for better IDE support:
Keep middleware focused
Keep middleware focused
Each middleware should have a single, clear responsibility:
Related Topics
Built-in Middleware
Explore built-in middleware for reference
Third-Party Middleware
Learn about external middleware packages