mapresponsewith_state in Axum

Learn how to write Axum middleware that changes outgoing responses while reading shared application state, with complete beginner examples and explanations

A handler produces a response, and sometimes that response needs changing before it leaves the server. The change often depends on something the application already knows. A configuration value decides how long a response may be cached. An application name decides which server header to stamp. A feature flag decides whether a header appears at all. The response alone does not carry that information, so the middleware needs a second input, the shared state of your application.

map_response_with_state is the helper for exactly that job. It builds middleware from a small async function that receives your application state and the response your handler produced, changes the response, and returns it. It is the state-aware version of the plain response helper, and the two share the same shape, with state added on top.

What map_response_with_state Does

Think of the handler as a kitchen that plates a dish, and this helper as the pass where the dish is checked before it leaves for the table. The pass can add a label, change the plate, or leave the dish alone. The shared state is the book of approved labels sitting on the pass, and map_response_with_state is the instruction that tells the pass which book to use. Change the book and the labelling changes, without rewriting the kitchen.

The helper itself has this signature:

pub fn map_response_with_state<F, S, T>(
    state: S,
    f: F,
) -> MapResponseLayer<F, S, T>

You pass two things. The first is the state value, usually a struct you defined that holds configuration or shared data. The second is the async function that transforms the response. The return value is a layer, which is the Tower term for a piece of middleware you can attach to a router. You do not need to understand the generic letters F, S, and T to use it. F is your function, S is your state type, and T describes the extractors your function uses.

Response middleware runs on the way out:

Response middleware runs after your handler has produced a response. The request has already been processed, and the response is on its way back to the client. Anything this function does happens between the handler finishing and the client receiving the response.

The Function You Write and Its Signature

The async function you write has a fixed shape. It takes one or more extractors first, and the response last. The State extractor is how the function receives the state you passed in.

async fn my_middleware<B>(
    State(state): State<AppState>,
    response: Response<B>,
) -> Response<B> {
    response
}

AppState is the name of the state struct in this example. Your own struct will have a different name, and the pattern stays the same. State(state) pulls the state value out of the extractor, so state inside the function is your struct.

The letter B stands for the body type of the response. A response body can be plain text, JSON bytes, or a stream, and each of those has a different Rust type. Writing Response<B> keeps the function generic, so it works with whatever body the handler produced. Many beginners write Response instead, which is a shorthand for Response<Body> using Axum's standard body type, and that works when your handlers use the standard body.

The return type can be Response<B> when you are changing the same response, or anything that implements IntoResponse when you want to build a new response from the old one. IntoResponse is the trait for values Axum can turn into an HTTP response, and a tuple of headers plus a response implements it, which makes adding headers a one-liner.

The response must be the last argument:

Extractors come first, and the response comes last. When you put Response<B> before State<AppState>, the compiler rejects the function because it no longer matches the shape Axum expects. The error mentions a trait bound on the function, which is the compiler's way of saying the argument order is wrong.

A First Complete Example

Start with the smallest useful case, adding a header to every response using a value stored in state. The state holds the application name, and the middleware stamps it onto the response.

Cargo.toml
[package]
name = "map-response-state-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
src/main.rs
use axum::{
    extract::State,
    http::HeaderValue,
    middleware::map_response_with_state,
    response::Response,
    routing::get,
    Router,
};

#[derive(Clone)]
struct AppState {
    app_name: String,
}

async fn stamp_app_name<B>(
    State(state): State<AppState>,
    mut response: Response<B>,
) -> Response<B> {
    let value = HeaderValue::from_str(&state.app_name).unwrap();
    response.headers_mut().insert("x-powered-by", value);
    response
}

async fn hello(State(state): State<AppState>) -> String {
    format!("Hello from {}!", state.app_name)
}

#[tokio::main]
async fn main() {
    let state = AppState {
        app_name: "My Axum App".to_string(),
    };
    let app = Router::new()
        .route("/", get(hello))
        .route_layer(map_response_with_state(state.clone(), stamp_app_name))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Run the server with cargo run, then send a request:

curl -i http://127.0.0.1:3000/

You will see a header line like this in the output:

x-powered-by: My Axum App

The handler also reads the state, and it returned Hello from My Axum App! as the body. The middleware read the same value and stamped it onto the response headers. One shared value fed both the body and the header, and changing app_name in one place changes both.

The middleware takes mut response because inserting a header changes the response, and Rust requires the mut keyword for that. When you forget mut, the compiler tells you the response cannot be borrowed as mutable, which is its way of pointing at the missing keyword.

Check that the header appears:

Run the server, send a request to /, and look at the response headers. When you see x-powered-by: My Axum App, the middleware is connected correctly. When the header is missing, check that the layer is attached to the route and that the state value is not empty.

Why the State Is Passed Twice

In the example above, the state appears in two places. The middleware receives state.clone(), and the router receives state through .with_state(state). That duplication confuses beginners, so it is worth spelling out what each copy does.

.with_state(state) tells the router which value to give to handlers that ask for State<AppState>. The first argument to map_response_with_state tells the middleware which value to give to its own State extractor. They are two separate deliveries of the same value, and they do not have to be the same value at all. You could pass a small configuration struct to the middleware while the router hands handlers a database pool. In most applications both values are the same shared state, which is why the example clones it once for the middleware and moves the original into .with_state.

The state must be Clone, Send, Sync, and 'static. Clone is required because the layer clones the state for each request. Send and Sync are required because requests are handled at the same time on different threads. 'static means the state cannot borrow from local variables that will disappear while the server is still running. A struct that owns its data, such as a String or a number, satisfies all four.

State without Clone will not compile:

When you remove #[derive(Clone)] from AppState, the compiler rejects map_response_with_state with a trait bound error mentioning Clone. The same happens when a field inside the struct does not implement Clone. Derive Clone on the struct and check every field type it contains.

Reading State, Path Parameters, and Headers Together

map_response_with_state allows more than one extractor, as long as every extractor implements FromRequestParts. That trait is the name for extractors that read from the request without consuming its body. Path, Query, HeaderMap, and State all fit.

This example reads a path parameter and the shared state, then adds a tag header to the response. The handler also reads the same path parameter, which shows that the middleware and the handler can both inspect the original request.

src/main.rs
use axum::{
    extract::{Path, State},
    http::HeaderValue,
    middleware::map_response_with_state,
    response::Response,
    routing::get,
    Router,
};

#[derive(Clone)]
struct AppState {
    app_name: String,
}

async fn tag_user_response<B>(
    State(state): State<AppState>,
    Path(id): Path<String>,
    mut response: Response<B>,
) -> Response<B> {
    let tag = format!("{}-user-{}", state.app_name, id);
    let value = HeaderValue::from_str(&tag).unwrap();
    response.headers_mut().insert("x-user-tag", value);
    response
}

async fn user_profile(Path(id): Path<String>) -> String {
    format!("Profile for user {}", id)
}

#[tokio::main]
async fn main() {
    let state = AppState {
        app_name: "Demo".to_string(),
    };
    let app = Router::new()
        .route("/users/{id}", get(user_profile))
        .route_layer(map_response_with_state(state.clone(), tag_user_response))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

When you request /users/42, the response carries the header x-user-tag: Demo-user-42, and the body says Profile for user 42. The middleware received Path("42") before the handler ran, and then it received the response after the handler finished. It combined the application name from state with the path value to produce the tag.

The timing here is easy to miss, and it explains why request-based extractors still work in a response-focused helper. The extractors run on the request parts before the handler is called. The transformation itself runs after the handler. The function straddles both moments, so it can read the path from the request and also change the response the handler returned.

Only FromRequestParts extractors are allowed:

Extractors such as Json<T> and Form<T> consume the request body and implement FromRequest, not FromRequestParts. They cannot be used as arguments here. When you try, the compiler rejects the function with a trait bound error about FromRequestParts. Stick to extractors that read without consuming the body, such as State, Path, Query, and HeaderMap.

Using Response Status and Headers in the Transformation

Response middleware can inspect the response before changing it. A realistic use case is caching. Only successful responses should receive a cache-control header, and the number of seconds should come from configuration stored in state.

src/main.rs
use axum::{
    extract::State,
    http::{header, HeaderValue},
    middleware::map_response_with_state,
    response::Response,
    routing::get,
    Router,
};

#[derive(Clone)]
struct AppState {
    cache_seconds: u64,
}

async fn add_cache_header<B>(
    State(state): State<AppState>,
    mut response: Response<B>,
) -> Response<B> {
    if response.status().is_success() && state.cache_seconds > 0 {
        let value = format!("public, max-age={}", state.cache_seconds);
        let header_value = HeaderValue::from_str(&value).unwrap();
        response
            .headers_mut()
            .insert(header::CACHE_CONTROL, header_value);
    }
    response
}

async fn public_page() -> &'static str {
    "This page can be cached"
}

async fn health(State(state): State<AppState>) -> String {
    format!("cache window is {} seconds", state.cache_seconds)
}

#[tokio::main]
async fn main() {
    let state = AppState {
        cache_seconds: 120,
    };
    let app = Router::new()
        .route("/page", get(public_page))
        .route("/health", get(health))
        .route_layer(map_response_with_state(state.clone(), add_cache_header))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request to /page returns a 200 OK response, so the middleware adds cache-control: public, max-age=120. A request to a route that returns a failure status will not receive the header, because the is_success() check fails. The state value controls the number, so changing the configuration changes the header without editing the middleware.

The order of operations inside the function is worth noticing. The status check happens first, then the header is inserted. When the status is not successful, the function returns the response unchanged. This pattern of inspect, decide, then change keeps response middleware readable and predictable.

Returning a New Response Instead of Changing the Old One

Sometimes you do not want to change the existing response in place. You want to build a new response with different headers, a different body, or a different status. The function can return anything that implements IntoResponse, which gives you the same flexibility as a handler.

This example adds a server header by returning a tuple of headers and the original response. Axum knows how to turn that tuple into a complete response. Note the concrete Response type in the function signature. That matters, because the generic Response<B> form cannot express a tuple return cleanly, and the compiler will reject the generic version with a trait bound error about the body type.

src/main.rs
use axum::{
    extract::State,
    http::{header, HeaderValue},
    middleware::map_response_with_state,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};

#[derive(Clone)]
struct AppState {
    server_name: String,
}

async fn add_server_header(
    State(state): State<AppState>,
    response: Response,
) -> impl IntoResponse {
    let server = HeaderValue::from_str(&state.server_name).unwrap();
    ([(header::SERVER, server)], response)
}

async fn home(State(state): State<AppState>) -> String {
    format!("served by {}", state.server_name)
}

#[tokio::main]
async fn main() {
    let state = AppState {
        server_name: "demo-server".to_string(),
    };
    let app = Router::new()
        .route("/", get(home))
        .route_layer(map_response_with_state(state.clone(), add_server_header))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The function no longer needs mut response, because it does not change the original response value. It creates a header array and pairs it with the response, and Axum converts the pair into a single response, merging the header into the final output. A request returns the body served by demo-server and a server: demo-server header.

This approach is useful when you want to add headers without touching the original response value, or when you want to replace the response entirely. When you replace the response, make sure the new one still has a sensible status code and content type. The client will see whatever you return, not what the handler originally produced.

Concrete Response when returning impl IntoResponse:

When the function returns impl IntoResponse instead of Response<B>, use the concrete Response type for the response argument. The generic body type B has no bounds that let the compiler prove the tuple conversion works, and the generic version fails to compile. The concrete type carries Axum's standard body, so the conversion is straightforward.

Where to Attach the Middleware

map_response_with_state returns a MapResponseLayer, which is a Tower layer. You attach it to a router with .layer() or .route_layer(), and the two attach points behave differently for requests that match no route.

.route_layer() applies the middleware only to requests that match a route. A request that falls through to the 404 fallback does not run the middleware, so a 404 response will not carry your stamped header. .layer() applies the middleware to every request that passes through that router, including requests that do not match a route and end up in the fallback, so the header appears on 404 responses too.

For a header that should appear on every response, including error pages, .layer() is the safer choice. For a header that only makes sense on real routes, .route_layer() is enough. This distinction matters for response middleware in particular, because a missing header on a 404 page is often the first sign that the middleware was attached with the wrong method.

The same program can show both behaviours. Attach the layer with .route_layer() and request an unknown path, and the header is absent. Attach it with .layer() instead, and the same unknown path returns the header. The handler never runs in either case, because there is no route to match, but .layer() still runs the middleware around the fallback response.

Ordering When More Than One Layer Is Attached

Order also matters when you attach more than one response middleware. With .layer(first).layer(second), second wraps first, so on the way in second runs before first, and on the way out first processes the response before second. When you need a specific response header to be the final word, attach that middleware last, so it sees the response after the other layers have finished. When two layers write the same header, the one added later wins, because it runs later on the response path. The same rule applies to route_layer calls. Each call wraps the routes that already exist, so the last call added ends up outermost and sees the request first and the response last.

A missing header on a 404 page points at the attach point:

When a stamped header appears on real routes but not on 404 responses, the middleware is probably attached with .route_layer(). Switch to .layer() when the header belongs on every response your server sends, including the ones produced by the fallback.

Common Mistakes and Compiler Errors

The most common mistake is forgetting Clone on the state type. The layer clones the state for each request, so a state struct without Clone produces a trait bound error. A related mistake is using a field type that does not implement Clone, such as a file handle or a non-cloneable client.

Another common mistake is forgetting mut on the response parameter. Inserting or removing headers requires mutable access. When the compiler says the response cannot be borrowed as mutable, add mut in front of the parameter name.

Using a body-consuming extractor is also a frequent source of confusion. Json<T> reads the request body, so it cannot be used before the handler in this middleware. The same applies to Form<T> and any other extractor built on FromRequest. Stick to extractors that implement FromRequestParts.

A fourth mistake is returning Response<B> while trying to build a new response with a different body type. When the new response has a different body, return impl IntoResponse instead, with a concrete Response argument, or convert the new response into the expected type before returning it. The compiler error usually mentions a type mismatch between Response<Body> and a response carrying some other body type.

Body-consuming extractors will not compile here:

When you add Json(payload): Json<MyType> as an argument to a map_response_with_state function, the compiler rejects it. The response middleware runs its extractors before the handler, but it is not allowed to consume the request body. The body belongs to the handler.

How It Differs from the Plain Response Helper and the Bracketing Form

The plain response helper without state is the same tool with the state slot empty. Axum implements it as the state-aware helper called with an empty state value, so the two are one mechanism with different call shapes. When your transformation function does not need shared state, the plain helper is shorter and communicates that fact clearly. When it does need state, the _with_state form is the one to use.

A bracketing helper is also state-aware, but it runs code before the handler and passes control onward explicitly. It is the right choice when you need to reject a request, change the request, or run logic before the handler. map_response_with_state is the right choice when you need to work with the response that the handler already produced.

A simple decision framework helps here. When your logic needs to inspect or change the incoming request and may stop the handler from running, use a request-focused helper. When your logic needs to stamp, rewrite, or inspect the outgoing response, use a response-focused helper. When the logic needs shared state in either case, use the _with_state version of that helper.

Summary

map_response_with_state is a focused tool for one job, changing a response after a handler has produced it, while reading shared application state. The state is passed directly to the middleware, so the middleware does not depend on the router's state being configured in a particular way. The transformation function receives extractors first and the response last, and it returns either the changed response or a new response through IntoResponse.

The most important insight is the split in timing. The extractors run before the handler, but the transformation runs after the handler. That is why the middleware can read a path parameter and also change the response the handler returned. Once that timing is clear, the rest of the API becomes a matter of choosing the right extractors, returning the right type, and attaching the layer to the right scope. When the response needs a change and the change depends on configuration or shared data, this helper is the fit. When the same change needs no state, the plain helper is shorter. When the logic must run before the handler instead of after it, a request-focused helper is the fit.