maprequestwith_state in Axum

Learn how to use axum middleware map_request_with_state to change incoming requests using shared application state, with complete beginner examples and explanations

Some requests need changing before they reach a handler, and the change depends on something your application already knows. A configuration value decides which header to add. A feature flag decides which path prefix to strip. A shared counter decides which number to stamp on the request. The request alone does not carry that information, so the middleware needs a second input, the shared state of your application.

map_request_with_state is the helper for exactly that job. It builds middleware from a small async function that receives your application state and the incoming request, changes the request, and hands it onward. The function can also stop the request early when the state says it should not continue.

What map_request_with_state Does

A handler receives a request and produces a response. Middleware sits between the client and the handler, and it can change the request on the way in. map_request_with_state creates that middleware from an async function you write. The function receives the state first, through the State extractor, then any other extractors it needs, and finally the request itself. It returns the request, usually changed, or it returns an error that becomes a response.

A mailroom gives a useful picture. The handler is the department that opens the parcel. The middleware is the mailroom that stamps the parcel before it goes upstairs. The shared state is the book of rules the mailroom checks, and map_request_with_state is the instruction that tells the mailroom which book to use. Change the book and the stamping changes, without rewriting the mailroom.

The helper itself has this signature:

pub fn map_request_with_state<F, S, T>(state: S, f: F) -> MapRequestLayer<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 request. 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.

A layer is middleware you can attach:

A layer wraps a router or a route. When a request arrives, it passes through each attached layer before it reaches a handler. map_request_with_state returns a layer, so you attach it with .layer() or .route_layer() exactly like any other middleware layer.

The Shape of the Function You Write

The async function you pass in has a fixed shape. Extractors come first, and the request comes last. The State extractor is always first when your function needs state.

async fn my_middleware<B>(
    State(state): State<AppState>,
    request: axum::http::Request<B>,
) -> axum::http::Request<B> {
    request
}

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 request. A request body can be plain text, JSON bytes, a file upload, or an empty body, and each of those has a different Rust type. Writing Request<B> keeps the function generic, so it works with whatever body the client sent. You do not pick a concrete body type. Axum fills B in for you.

The extractors before the request must implement FromRequestParts. That trait is the name for extractors that read from the request without consuming its body. State, Path, Query, and HeaderMap all implement it. Extractors that read the body, such as Json<T> and Form<T>, implement a different trait called FromRequest, and they cannot appear here, because the body still has to reach the handler untouched.

The function can also return a Result instead of a plain request:

async fn my_middleware<B>(
    State(state): State<AppState>,
    request: axum::http::Request<B>,
) -> Result<axum::http::Request<B>, axum::http::StatusCode> {
    Ok(request)
}

Ok(request) means the request continues to the handler. Err(...) means the request stops here and the error value becomes the response. The error type must implement IntoResponse, which is the trait for values Axum can turn into an HTTP response. StatusCode implements it, so Err(StatusCode::BAD_REQUEST) becomes a plain 400 response. A tuple like (StatusCode, &str) also implements it, so you can attach a message body to the rejection.

A First Complete Example

The smallest useful example reads a value from state and stamps it onto the request as a header. The handler then reads that header back, which proves the middleware ran and the state reached it.

Create a new project and put these dependencies in Cargo.toml:

Cargo.toml
[package]
name = "map-request-state"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tower = "=0.5.3"

Now write src/main.rs:

src/main.rs
use axum::{
    extract::{Request, State},
    middleware,
    response::IntoResponse,
    routing::get,
    Router,
};

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

async fn stamp_from_state<B>(
    State(state): State<AppState>,
    mut request: axum::http::Request<B>,
) -> axum::http::Request<B> {
    request.headers_mut().insert(
        "x-custom-header",
        state.custom_header.parse().unwrap(),
    );
    request
}

async fn handler(req: Request) -> impl IntoResponse {
    let header_value = req
        .headers()
        .get("x-custom-header")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("missing")
        .to_string();
    format!("Header value: {}", header_value)
}

#[tokio::main]
async fn main() {
    let state = AppState {
        custom_header: "hello-from-state".to_string(),
    };
    let app = Router::new()
        .route("/", get(handler))
        .route_layer(middleware::map_request_with_state(state.clone(), stamp_from_state))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Listening on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

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

curl http://127.0.0.1:3000/

You will see this output:

Header value: hello-from-state

The handler never knew the value came from state. It only saw a header called x-custom-header on the request. The middleware read custom_header out of AppState, inserted it as a header, and passed the request on. That separation is the point. The handler stays simple, and the stamping logic lives in one place where you can change it without touching any handler.

Three details in this program deserve attention. The mut on request is required because inserting a header changes the request, and Rust will not let you change a value you did not declare mutable. The state.clone() in the map_request_with_state call gives the middleware its own copy of the state, while the original moves into .with_state(state) for the router. And route_layer attaches the middleware to the routes that already exist on the router, so the layer only runs when a request matches the / route.

Seeing the stamped value means the wiring works:

If the response shows Header value: hello-from-state, the state reached the middleware and the middleware ran before the handler. If it shows missing, the layer is not attached to the route, so check the .route_layer(...) line and make sure it comes after .route(...).

Why State Appears Twice

In the example above, the state value 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 hand to handlers that ask for State<AppState>. The first argument to map_request_with_state tells the middleware which value to hand 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. The middleware could receive a small configuration struct while the router hands handlers a database pool. In practice the two are usually the same shared state, which is why examples clone it once for the middleware and move the original into the router.

The state type must satisfy four bounds. It must be Clone, because the layer clones the state for each request it handles. It must be Send and Sync, because requests are handled at the same time on different threads, and the state has to be safe to share across those threads. It must be 'static, which means it cannot borrow data from a local variable 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. A struct holding a reference to a local variable does not.

State without Clone will not compile:

If you remove #[derive(Clone)] from AppState, the compiler rejects map_request_with_state with a trait bound error mentioning Clone. The same happens when a field inside the struct does not implement Clone, for example a field holding a type that cannot be copied or cloned. Derive Clone on the struct and on every field type it contains.

Rejecting a Request Using State

Because the function may return a Result, it can reject a request early, and the decision can depend on state. Suppose every request must carry a particular header, and the name of that header comes from configuration. When the header is missing, the middleware answers with a 400 Bad Request and the handler never runs.

src/main.rs
use axum::{
    extract::State,
    http::StatusCode,
    middleware,
    routing::get,
    Router,
};

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

async fn handler() -> &'static str {
    "Request passed validation"
}

async fn require_header<B>(
    State(state): State<AppState>,
    request: axum::http::Request<B>,
) -> Result<axum::http::Request<B>, StatusCode> {
    if request.headers().contains_key(state.required_header.as_str()) {
        Ok(request)
    } else {
        Err(StatusCode::BAD_REQUEST)
    }
}

#[tokio::main]
async fn main() {
    let state = AppState {
        required_header: "x-auth-token".to_string(),
    };
    let app = Router::new()
        .route("/", get(handler))
        .route_layer(middleware::map_request_with_state(state.clone(), require_header))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Send a request without the header:

curl -i http://127.0.0.1:3000/

The response starts with HTTP/1.1 400 Bad Request, and the handler never runs. Send the request with the header, and the handler answers:

curl -i -H "x-auth-token: anything" http://127.0.0.1:3000/

The response is 200 OK with the body Request passed validation. The middleware read the required header name from state, checked the request, and either passed it on or rejected it. Changing the configuration value changes which header is required, without editing the middleware code.

The error type can be anything that implements IntoResponse. StatusCode is the convenient choice when a bare status is enough. A (StatusCode, &str) tuple works when you want a message body too, for example Err((StatusCode::BAD_REQUEST, "missing x-auth-token")). Either way, the rejection happens before the handler, so no handler code runs for a request that fails the check.

The error type must implement IntoResponse:

The error type in the Result return must implement IntoResponse. When you invent your own error type, you must implement that trait for it, or the compiler will reject the middleware function. StatusCode and tuples of a status code with a string body already implement it, so they are the safe choices while learning.

Rewriting the Request Path from State

A request path can also come from state. A common case is stripping a version prefix such as /api/v1 so handlers see clean paths, while the prefix itself lives in configuration and can change without editing the middleware.

src/main.rs
use axum::{
    extract::{Request, State},
    http::Uri,
    middleware,
    routing::get,
    Router,
};

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

async fn handler(req: Request) -> String {
    format!("Request path: {}", req.uri().path())
}

async fn strip_prefix<B>(
    State(state): State<AppState>,
    mut request: axum::http::Request<B>,
) -> axum::http::Request<B> {
    let original_path = request.uri().path().to_string();
    if let Some(new_path) = original_path.strip_prefix(&state.prefix) {
        let query = request
            .uri()
            .query()
            .map(|q| format!("?{q}"))
            .unwrap_or_default();
        let new_uri: Uri = format!("{new_path}{query}").parse().unwrap();
        *request.uri_mut() = new_uri;
    }
    request
}

#[tokio::main]
async fn main() {
    let state = AppState {
        prefix: "/api/v1".to_string(),
    };
    let app = Router::new()
        .route("/api/v1/hello", get(handler))
        .route_layer(middleware::map_request_with_state(state.clone(), strip_prefix))
        .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 /api/v1/hello reaches the handler, and the handler reports Request path: /hello, because the middleware removed the prefix before passing the request on. A request to a path that does not start with the prefix is left unchanged. The route stays /api/v1/hello because the middleware runs after routing has matched, so the rewrite changes what the handler sees, not which route matches.

Preserve the query string when rewriting the URI:

The example rebuilds the query string by hand, because building a new Uri from only the path would drop it. When you rewrite a URI, a request to /api/v1/hello?lang=en must still carry ?lang=en after the rewrite, or your handlers will lose their query parameters. Copy the query across every time you build a new URI.

Doing Async Work with State

The function is async, so it can await while it decides how to change the request. That matters when the state itself needs an async operation, for example a counter guarded by an async lock, or a value fetched from another service. A synchronous function could not wait for those.

This example keeps a shared request counter in state and stamps each request with its number. The counter lives behind a tokio::sync::Mutex, which is a lock designed for async code, and locking it requires .await.

src/main.rs
use axum::{
    extract::{Request, State},
    middleware,
    routing::get,
    Router,
};
use std::sync::Arc;
use tokio::sync::Mutex;

#[derive(Clone)]
struct AppState {
    counter: Arc<Mutex<u64>>,
}

async fn stamp_count<B>(
    State(state): State<AppState>,
    mut request: axum::http::Request<B>,
) -> axum::http::Request<B> {
    let mut count = state.counter.lock().await;
    *count += 1;
    let value = count.to_string();
    request
        .headers_mut()
        .insert("x-request-number", value.parse().unwrap());
    request
}

async fn handler(req: Request) -> String {
    let number = req
        .headers()
        .get("x-request-number")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("?")
        .to_string();
    format!("You are request number {}", number)
}

#[tokio::main]
async fn main() {
    let state = AppState {
        counter: Arc::new(Mutex::new(0)),
    };
    let app = Router::new()
        .route("/", get(handler))
        .route_layer(middleware::map_request_with_state(state.clone(), stamp_count))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The first request answers You are request number 1, the second answers You are request number 2, and so on. Each request waits its turn for the lock, increments the shared number, and stamps the result onto the request before the handler sees it.

Arc is short for atomic reference counted pointer. It lets several owners share the same value, and cloning an Arc only copies a cheap handle, not the data underneath. The Mutex inside it is what makes mutation safe when many requests run at the same time. Without the lock, two requests could read the same number and stamp duplicates. A standard library Mutex would also work here, but holding it across an .await point can block the async runtime, so the Tokio version is the right tool when the lock is held while awaiting.

One caution applies to async work in this function. The function runs before the handler, so slow work here delays every request. A quick lock or a fast lookup is fine. A slow call to another service on every request will make the whole application feel slow, and that cost belongs in a cache or in the handler, not in request middleware.

The Tower Alternative, Capturing State in a Closure

There is a second, older way to give a request transformation access to state. Tower, the library Axum builds on, offers a synchronous map_request that takes a plain closure instead of an async function. It knows nothing about Axum's State extractor, so the only way to give it state is to capture the state in the closure itself, usually by cloning an Arc into it with the move keyword, and the closure can neither fail nor await. Prefer axum::middleware::map_request_with_state when you are writing Axum middleware. It is async, it receives state through the State extractor the same way handlers do, and it can reject requests. Use Tower's version only when you are already working inside Tower's layer system and need a tiny synchronous transformation there.

Combining with Other Layers

You can combine map_request_with_state with other middleware layers using ServiceBuilder, which is Tower's builder for stacking several layers into one. The order you list them in is the order they run on the way in. The first layer listed is the outermost, so it sees the request first.

This example sets a static request id header with a ready-made Tower layer, then adds a second header from state with map_request_with_state:

src/main.rs
use axum::{
    extract::{Request, State},
    http::header,
    middleware,
    routing::get,
    Router,
};
use tower::ServiceBuilder;
use tower_http::set_header::SetRequestHeaderLayer;

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

async fn handler(req: Request) -> String {
    let request_id = req
        .headers()
        .get("x-request-id")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("none")
        .to_string();
    let extra = req
        .headers()
        .get("x-extra")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("none")
        .to_string();
    format!("Request ID: {}, Extra: {}", request_id, extra)
}

async fn add_extra<B>(
    State(state): State<AppState>,
    mut request: axum::http::Request<B>,
) -> axum::http::Request<B> {
    request
        .headers_mut()
        .insert("x-extra", state.extra_header.parse().unwrap());
    request
}

#[tokio::main]
async fn main() {
    let state = AppState {
        extra_header: "extra-value".to_string(),
    };
    let app = Router::new()
        .route("/", get(handler))
        .layer(
            ServiceBuilder::new()
                .layer(SetRequestHeaderLayer::overriding(
                    header::HeaderName::from_static("x-request-id"),
                    header::HeaderValue::from_static("12345"),
                ))
                .layer(middleware::map_request_with_state(state.clone(), add_extra)),
        )
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request answers Request ID: 12345, Extra: extra-value. SetRequestHeaderLayer::overriding sets the x-request-id header to a fixed value, replacing any value the client sent. The state-driven function then adds x-extra. Because ServiceBuilder runs layers in the order they are listed, the set-header layer runs first and the state function runs second, and both headers are present when the handler reads them.

This snippet needs tower-http with the set-header feature enabled in Cargo.toml:

Cargo.toml
tower-http = { version = "=0.7.1", features = ["set-header"] }

ServiceBuilder order is top to bottom:

With ServiceBuilder, the first layer listed runs first on the request. That is the opposite of repeated .layer() calls on a router, where the last call added is the outermost and runs first. When you mix the two styles, keep the two orderings straight, or your headers will be set in the wrong order and a later layer may overwrite an earlier one.

Common Mistakes

Forgetting Clone on the State

The layer clones the state for each request. A state struct without Clone produces a trait bound error, and so does a field inside the struct that does not implement Clone. Derive Clone on the struct and check every field.

Putting the Request Before the Extractors

Extractors come first, and the request comes last. When you put Request<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.

Using a Body-Consuming Extractor

Extractors such as Json<T> and Form<T> consume the request body and implement FromRequest, not FromRequestParts. They cannot be used as arguments here, because the body still has to reach the handler. Stick to extractors that implement FromRequestParts, such as State, Path, Query, and HeaderMap.

Returning Ok(req) from Tower map_request

Tower's combinator is infallible, so its closure returns the request directly, not a Result. Wrapping the return value in Ok(...) is the most common compile error when people move between the two APIs. Ok and Err belong to Axum's map_request and map_request_with_state, where rejection is a real feature.

Trying to Change Shared State Without Interior Mutability

The State extractor and a captured Arc only give you shared access. To change state from inside the middleware, use a Mutex, RwLock, or an atomic type inside the state struct, as the counter example does. Plain fields on the state struct cannot be mutated through a shared reference.

Summary

map_request_with_state answers one question: how do I change a request when the change depends on something my application already knows? Pass the state and an async function, receive the state through the State extractor first, any other extractors next, and the request last, then return the changed request, or a Result that rejects it early. The state must be Clone + Send + Sync + 'static, and it is usually the same value the router receives through .with_state, cloned once for the middleware.

The decision framework is short. When the transformation only touches the incoming request and needs shared state, use map_request_with_state. When the same transformation needs no state, the plain form without state is shorter and says so clearly. When the transformation must be synchronous and tiny and you are already inside Tower's layer system, the captured Arc closure is the fallback. And when the logic needs to run after the handler, or to see the response as well as the request, a request-only helper is the wrong tool, because it only ever sees the request side of the exchange.