Skip to main content
Middleware allows you to process requests before they reach handlers and modify responses before they’re sent to clients. Axum supports both custom middleware and Tower middleware.

Middleware with from_fn

The simplest way to create middleware is using middleware::from_fn:

Middleware signature

Middleware functions created with from_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 using from_fn_with_state:

Modifying requests and responses

Transform the request before it reaches handlers:

Layer ordering

Middleware layers are applied in reverse order. The last layer added is executed first.

Tower middleware

Use any Tower middleware with Axum:

Route-specific middleware

Apply middleware to specific routes:
Alternatively, use route_layer:

Common middleware patterns

For production, use the tower-http CORS layer instead.

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