from_fn module provides a simple way to create middleware from async functions, allowing you to intercept and modify requests before they reach handlers and responses before they’re returned to clients.
Core functions
from_fn
- Must be an
async fn - Take zero or more
FromRequestPartsextractors - Take exactly one
FromRequestextractor as the second to last argument - Take
Nextas the last argument - Return something that implements
IntoResponse
from_fn_with_state
Request/response handling patterns
Modifying requests
Insert headers or modify the request before it reaches handlers:Processing request body
Consume and inspect the request body:Processing request and response
Handle both request and response in the same middleware:Running extractors
Use extractors to access request data:Passing data to handlers
Use request extensions to pass data from middleware to handlers:Tracking metrics
Implement request tracking and metrics:The Next type
Methods
run
Types
FromFnLayer
tower::Layer created from an async function. Created with from_fn or from_fn_with_state.
FromFn
ResponseFuture
FromFn.
See also
- middleware overview - Introduction to axum middleware
- tower integration - Using tower middleware with axum
- extractors - Learn about request extractors