Generating Middleware
The fastest way to create a new middleware is using the Kit CLI:- Create
src/middleware/auth.rswith a middleware stub - Update
src/middleware/mod.rsto export the new middleware
Overview
Middleware sits between the incoming request and your route handlers, allowing you to:- Authenticate and authorize requests
- Log requests and responses
- Add CORS headers
- Rate limit requests
- Transform request/response data
- And much more
Creating Middleware
To create middleware, define a struct and implement theMiddleware trait:
The handle Method
The handle method receives:
request: The incoming HTTP requestnext: A function to call the next middleware in the chain (or the route handler)
- Continue the chain: Call
next(request).awaitto pass control to the next middleware - Short-circuit: Return a response early without calling
next() - Modify the request: Transform the request before calling
next() - Modify the response: Transform the response after calling
next()
Short-Circuiting Requests
Return early to block a request from reaching the route handler:Registering Middleware
Kit supports three levels of middleware:1. Global Middleware
Global middleware runs on every request. Register it inbootstrap.rs using the global_middleware! macro:
2. Route Middleware
Apply middleware to individual routes using the.middleware() method:
3. Route Group Middleware
Apply middleware to a group of routes that share a common prefix:Middleware Execution Order
Middleware executes in the following order:- Global middleware (in registration order)
- Route group middleware
- Route-level middleware
- Route handler
Practical Examples
CORS Middleware
Rate Limiting Middleware
Request Timing Middleware
File Organization
The recommended file structure for middleware:Summary
| Feature | Usage |
|---|---|
| Create middleware | Implement Middleware trait |
| Global middleware | global_middleware!(MyMiddleware) in bootstrap.rs |
| Route middleware | .middleware(MyMiddleware) on route definition |
| Group middleware | .middleware(MyMiddleware) on route group |
| Short-circuit | Return Err(HttpResponse::...) without calling next() |
| Continue chain | Call next(request).await |