Creating middleware
Use themake:middleware Ace command to create a new middleware:
- server: Runs for all HTTP requests
- router: Runs for all matched routes
- named: Applied selectively to specific routes
app/middleware/auth_middleware.ts:
Middleware execution flow
Middleware execute in a pipeline:Middleware stacks
Server middleware
Server middleware runs for every HTTP request, even if the route doesn’t exist. Configure instart/kernel.ts:
- CORS handling
- Request logging
- Body parsing
- Setting global headers
Router middleware
Router middleware runs only for matched routes. Configure instart/kernel.ts:
- Authentication checks
- CSRF protection
- Rate limiting for all routes
Named middleware
Named middleware is applied selectively to specific routes. Register instart/kernel.ts:
Writing middleware logic
Authentication middleware
CORS middleware
Request logging middleware
Rate limiting middleware
Terminating requests early
Middleware can terminate the request without callingnext():
Middleware with parameters
Pass parameters to middleware:Applying middleware to route groups
Apply middleware to multiple routes using route groups:Nested middleware
Combine middleware from groups and individual routes:Middleware execution order
Middleware executes in this order:- Server middleware (all requests)
- Router middleware (matched routes only)
- Route group middleware (outer to inner groups)
- Route-specific middleware
- Route handler
Inline middleware
Define middleware inline for simple use cases:Best practices
Always call next()
Always call next()
Unless you’re intentionally terminating the request, always call
next() and return its output. Forgetting to call next() will cause requests to hang.Use appropriate middleware stack
Use appropriate middleware stack
- Use server middleware only for logic that applies to ALL requests
- Use router middleware for logic that applies to all matched routes
- Use named middleware for selective application to specific routes
Keep middleware focused
Keep middleware focused
Each middleware should have a single responsibility. If your middleware is doing multiple things, split it into separate middleware.
Handle errors gracefully
Handle errors gracefully
Wrap middleware logic in try-catch blocks to handle errors: