Middleware with from_fn
The simplest way to create middleware is using middleware::from_fn:
Middleware signature
Middleware functions created withfrom_fn must:
1
Be an async function
The middleware must be an
async fn.2
Take extractors (optional)
Can take zero or more
FromRequestParts extractors before the request.3
Take Request
Must take exactly one
Request as second-to-last argument.4
Take Next
Must take
Next as the last argument.5
Return IntoResponse
Must return something that implements
IntoResponse.Using extractors in middleware
Extract data from requests in middleware:Middleware with state
Access application state in middleware usingfrom_fn_with_state:
Modifying requests and responses
- Modify request
- Modify response
- Read request body
Transform the request before it reaches handlers:
Layer ordering
Tower middleware
Use any Tower middleware with Axum:Route-specific middleware
Apply middleware to specific routes:route_layer:
Common middleware patterns
Request logging
Request logging
CORS headers
CORS headers
Error handling in middleware
Handle middleware errors appropriately:Next steps
Error Handling
Learn how to handle errors from middleware
State
Use state in your middleware