map_response in Axum Middleware

Learn how to use axum middleware map_response to change HTTP responses after handlers run, with ordering rules, extractors, body handling, and complete beginner examples

A handler produces a response, and usually that response goes straight back to the client. Sometimes you want to step in between the two. Add a header to every response. Hide a status code from the outside world. Log the status before it leaves. Change a word in the body. Those are all jobs for the response side of middleware, and map_response is the smallest helper that does them.

map_response takes an async function, turns it into a layer, and runs that function on every response that passes through the layer. The function receives the response, changes it, and returns it. The original response is never sent to the client until your function returns.

What map_response Does

Think of the handler as a kitchen that plates a dish, and map_response as the pass where a dish is checked before it leaves for the table. The kitchen already did its work. The pass can add a garnish, swap the plate, or send the dish back, but it does not cook anything new. In the same way, map_response does not run your handler. It receives the finished response and decides what the client finally sees.

The helper has this signature:

pub fn map_response<F, T>(f: F) -> MapResponseLayer<F, (), T>

You give it one thing, an async function f, and you get back a layer you can attach to a router. The generic letters look dense, but the practical meaning is simple. F is your function, and T describes the extractors it uses. The () in the middle is the state slot, and it is empty here because this helper has no state. A companion helper fills that slot with real state, and it is the one to reach for when the response change depends on shared configuration.

The async function you write follows a fixed shape. Extractors come first, and the response comes last:

async fn my_middleware(response: Response) -> Response {
    response
}

Response here means axum::response::Response, which is a response carrying Axum's standard body type. That is the type to use in map_response functions. The bare http::Response type needs a body type parameter of its own, so writing http::Response without one does not compile. When you want the generic form, write Response<B>, where B is the body type of the response the handler produced.

Two facts about that function surprise beginners, so they are worth stating early. First, the function is async, so it can await while it works. Second, it is not limited to the response alone. Because it can run extractors that implement FromRequestParts, it can read request data such as the path, the query string, or headers before the handler runs. State is the one thing it cannot reach on its own, and that needs the state-aware companion helper.

A First Complete Example

Start with the simplest use, adding a custom header to every response. The handler returns a plain string, Axum turns it into a response, and the middleware adds a server header before the client sees it.

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

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

Now write src/main.rs:

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

async fn handler() -> &'static str {
    "Hello from the handler!"
}

async fn add_custom_header(mut response: Response) -> Response {
    response.headers_mut().insert(
        header::SERVER,
        HeaderValue::from_static("my-awesome-server"),
    );
    response
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(handler))
        .layer(middleware::map_response(add_custom_header));
    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 output like this:

HTTP/1.1 200 OK
server: my-awesome-server
content-length: 23
date: ...
Hello from the handler!

The server: my-awesome-server header was added by the middleware. The body Hello from the handler! is 23 bytes long, which is why the content-length is 23. The handler returned a simple string and never knew a header was added. That separation is the whole appeal. One function stamps every response, and no handler has to remember to do it.

The function takes mut response because inserting a header changes the response, and Rust requires the mut keyword for that. headers_mut() gives a mutable reference to the header map, so insert can add or replace a header in place. The body is never touched, so it streams through exactly as the handler produced it.

Seeing the custom header means the layer works:

If the curl output shows server: my-awesome-server, the layer is attached and running. If the header is missing, check the .layer(middleware::map_response(add_custom_header)) line and make sure it comes after the .route(...) call it should wrap.

How Layers Order Themselves on the Response Path

Middleware layers form an onion around the handler. The order you add them in decides who sees the response first, and that order catches beginners out, because it is the reverse of the request order.

When you write this:

let app = Router::new()
    .route("/", get(handler))
    .layer(layer_a)
    .layer(layer_b);

The layer added last is the outermost. layer_b wraps layer_a, which wraps the handler. A request meets layer_b first, then layer_a, then the handler. A response travels back the other way. It meets layer_a first, then layer_b, and only then leaves the server. The first layer added sees the response first, and the last layer added sees it last, which means the last layer added has the final word on the response.

This example makes the rule concrete. Two map_response layers both write the same header, so whichever runs second wins:

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

async fn add_header_one(mut response: Response) -> Response {
    response.headers_mut().insert(
        header::HeaderName::from_static("x-order"),
        "one".parse().unwrap(),
    );
    response
}

async fn add_header_two(mut response: Response) -> Response {
    response.headers_mut().insert(
        header::HeaderName::from_static("x-order"),
        "two".parse().unwrap(),
    );
    response
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(|| async { "hello" }))
        .layer(middleware::map_response(add_header_one))
        .layer(middleware::map_response(add_header_two));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request to / returns an x-order header with the value two. The response met add_header_one first, because it was added first and sits closest to the handler, and then it met add_header_two, which overwrote the header. The response path order is one and then two, which is the order the layers were added in. When two layers touch the same header, the one added later wins, because it runs later on the way out.

The last layer added has the final word:

The first .layer() call sees the response first, and the last .layer() call sees it last. When you want one piece of middleware to have the final say on a header or a status code, attach it last. When you want it to run before another layer on the response path, attach it earlier.

Running Extractors in map_response

A map_response function is not limited to the response it receives. It can also run extractors that implement FromRequestParts, which are the extractors that read from the request without consuming its body. Those extractors run before the handler, and their values are available when the function later processes the response.

src/main.rs
use axum::{
    extract::Path,
    middleware,
    response::Response,
    routing::get,
    Router,
};
use std::collections::HashMap;

async fn tag<B>(
    Path(path_params): Path<HashMap<String, String>>,
    response: Response<B>,
) -> Response<B> {
    let id = path_params.get("id").map(|s| s.as_str()).unwrap_or("?");
    println!("responding to user {}", id);
    response
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users/{id}", get(|| async { "ok" }))
        .layer(middleware::map_response(tag));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request to /users/42 prints responding to user 42 in the terminal, because Path read the route's path parameters from the original request before the handler ran. Query, HeaderMap, and Uri work the same way. What you cannot use here are extractors that consume the request body, such as Json<T> or Form<T>. Those implement FromRequest, not FromRequestParts, and the body still has to reach the handler. And when the value you need lives in shared application state rather than in the request, the state-aware companion helper is the one that can reach it.

Extractors run before the handler, the change runs after it:

The timing is easy to mix up. The extractors in a map_response function run on the request before the handler executes. The body of the function that changes the response runs after the handler has produced that response. The function straddles both moments, which is why it can read a path parameter and also change the response that the handler returned.

Returning Anything That Implements IntoResponse

The function does not have to return a Response. It can return anything that implements IntoResponse, which is often shorter when you only want to add headers to the handler's response:

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

async fn set_foo(response: Response) -> impl IntoResponse {
    ([("x-foo", "foo")], response)
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(|| async { "hello" }))
        .layer(middleware::map_response(set_foo));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The tuple ([("x-foo", "foo")], response) is a headers-plus-response pair, and Axum turns it into a complete response with the extra header merged in. Returning Response directly is still the right choice when you are changing the response in place, for example with headers_mut(). Returning impl IntoResponse is the right choice when you are building a new response from the old one, because the tuple form says in one line what would otherwise take a split, an insert, and a rebuild.

Changing the Status Code and Headers

So far the examples only added a header. In practice you will also want to change the status code, remove headers a handler should not have sent, or make a change only when the response meets a condition.

Hiding a 404 Status

Suppose a handler returns 404 Not Found for missing resources, but you want the outside world to see a plain 200 OK instead. Split the response into its parts, change the status, and rebuild it:

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

async fn handler() -> StatusCode {
    StatusCode::NOT_FOUND
}

async fn hide_not_found(response: Response) -> Response {
    let (mut parts, body) = response.into_parts();
    if parts.status == StatusCode::NOT_FOUND {
        parts.status = StatusCode::OK;
    }
    Response::from_parts(parts, body)
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(handler))
        .layer(middleware::map_response(hide_not_found));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request now returns HTTP/1.1 200 OK instead of 404. The body is untouched, which in this case is empty, because a bare StatusCode converts to an empty response. into_parts() splits a response into its parts, meaning status, headers, and version, plus the body. That split is what lets you change the status without losing the body, and Response::from_parts(parts, body) puts the two halves back together.

Removing a Header

Sometimes you want to strip a header a handler accidentally set, such as Server or X-Powered-By. headers_mut() reaches the header map directly, so no split is needed:

use axum::{http::header, response::Response};

async fn remove_server_header(mut response: Response) -> Response {
    response.headers_mut().remove(header::SERVER);
    response
}

Use headers_mut() when you only change headers. Use into_parts() when you also need to change the status, because the status lives in the parts, not in the header map. Both leave the body exactly as the handler produced it.

Adding a Header Only for Successful Responses

A cache header should only appear on successful responses, not on errors. Check the status first, then decide:

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

async fn add_cache_control(response: Response) -> Response {
    let (mut parts, body) = response.into_parts();
    if parts.status == StatusCode::OK {
        parts.headers.insert(
            header::CACHE_CONTROL,
            HeaderValue::from_static("max-age=60"),
        );
    }
    Response::from_parts(parts, body)
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(|| async { "Hello" }))
        .layer(middleware::map_response(add_cache_control));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Successful responses now carry cache-control: max-age=60, so browsers may reuse them for 60 seconds, while error responses stay uncached. The pattern is inspect, decide, then change, and it keeps response middleware readable. The check happens on the parts, the insert happens only when the check passes, and the response is returned unchanged in every other case.

Logging the Response Status

A small piece of response middleware can log every status code your server sends, without touching any handler. It needs tracing and tracing-subscriber in Cargo.toml, alongside the usual dependencies:

Cargo.toml
[package]
name = "map-response-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tracing = "0.1"
tracing-subscriber = "0.3"
src/main.rs
use axum::{
    middleware,
    response::Response,
    routing::get,
    Router,
};
use tracing::info;

async fn log_status(response: Response) -> Response {
    let status = response.status();
    info!("Response status: {}", status);
    response
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt::init();
    let app = Router::new()
        .route("/", get(|| async { "Hello" }))
        .layer(middleware::map_response(log_status));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

When you run this and send a request, the terminal shows a line like:

INFO map_response_demo: Response status: 200 OK

The logger reads the status, writes one line, and returns the response unchanged. When you also need request details in the same log line, add a Path, Query, or HeaderMap extractor as an argument, as shown in the extractor section above.

Inspecting and Changing the Response Body

Headers and status live in the response parts. The body is a different matter. The body of a response in Axum is axum::body::Body, which is a struct wrapping a boxed body. The body may be streaming, which means it is not necessarily stored fully in memory. It arrives in pieces, and the client may still be receiving it while your middleware runs.

When you need to look at the body bytes, you must collect them first. Axum provides a helper for that, axum::body::to_bytes:

pub async fn to_bytes(body: Body, limit: usize) -> Result<Bytes, Error>

It collects the whole body into Bytes, which is a chunk of bytes held in memory, or returns an error when the body is larger than the limit you pass. It does not return a response. You build the new response yourself from the bytes.

This example replaces every occurrence of the word hello with goodbye in the response body:

src/main.rs
use axum::{
    body::{to_bytes, Body},
    middleware,
    response::Response,
    routing::get,
    Router,
};

async fn handler() -> &'static str {
    "hello world"
}

async fn replace_hello(response: Response) -> Response {
    let (parts, body) = response.into_parts();
    let bytes = to_bytes(body, usize::MAX).await.unwrap();
    let content = String::from_utf8(bytes.to_vec()).unwrap();
    let new_content = content.replace("hello", "goodbye");
    Response::from_parts(parts, Body::from(new_content))
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(handler))
        .layer(middleware::map_response(replace_hello));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request now returns goodbye world. The middleware split the response, buffered the body, did a string replacement, wrapped the new string back into a Body with Body::from, and rebuilt the response. The status and headers from the original parts survived untouched.

Buffering the body breaks streaming:

Reading the full body into memory with to_bytes defeats the purpose of a streaming response. When a handler returns a large file or a stream of events, buffering it means holding the whole thing in memory and delaying the first byte until the last byte arrives. Only buffer when you truly need to change the body bytes, and pass a real size limit instead of usize::MAX when you know how large the body should be. When you only need to add a header, use headers_mut() and leave the body alone.

When the Transformation Can Fail

A body transformation can fail. Parsing the body as JSON is the classic case. The function must still return a response, so you decide inside the function what to return when the work fails. This example tries to parse the response body as JSON and prettify it. When parsing fails, it returns a 500 Internal Server Error with a plain text message:

src/main.rs
use axum::{
    body::{to_bytes, Body},
    http::StatusCode,
    middleware,
    response::Response,
    routing::get,
    Router,
};

async fn handler() -> &'static str {
    "not-json"
}

async fn prettify_json(response: Response) -> Response {
    let (parts, body) = response.into_parts();
    let bytes = to_bytes(body, usize::MAX).await.unwrap();
    match serde_json::from_slice::<serde_json::Value>(&bytes) {
        Ok(value) => {
            let pretty = serde_json::to_string_pretty(&value).unwrap();
            Response::from_parts(parts, Body::from(pretty))
        }
        Err(_) => {
            let mut error_response = Response::new(Body::from("Invalid JSON in response"));
            *error_response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
            error_response
        }
    }
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(handler))
        .layer(middleware::map_response(prettify_json));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Send a request and you will see:

HTTP/1.1 500 Internal Server Error
content-type: text/plain
Invalid JSON in response

The handler returned not-json, which is not valid JSON, so the middleware took the failure branch and built a fresh error response with Response::new and a status set through status_mut(). This snippet needs serde_json = "1" in Cargo.toml. The pattern generalises. Whenever a transformation can fail, handle the failure inside the function and return a sensible response, because the function has no way to report an error to Axum except by returning a response.

What map_response Cannot Do

map_response only sees the response after the handler has finished, so it cannot capture anything from before the handler ran, unless that thing is in the request itself. A start timestamp is the clearest example. To measure how long a handler took, the start time has to be recorded before the handler starts, and map_response has no code that runs at that moment.

One fix is to store the start time in request extensions with a request-side helper, and read it back later. The more direct fix is a middleware form that brackets the handler call, giving you code before and after it in one function. That form records the start time, passes control onward to the rest of the stack, and changes the response when it comes back. The line that passes control onward is the pivot. Everything before it runs on the request, and everything after it runs on the response. When you need a value from before the handler ran that is not in the request, reach for that bracketing form. When the work is purely about the finished response, map_response is the smaller and clearer tool.

Common Mistakes

Forgetting to Return the Response

The function must return a Response or something that implements IntoResponse. When a function ends without a final expression, or ends with () because the last line is a statement with a semicolon, the compiler complains. Always check that the function ends with response or a constructed Response.

Thinking map_response Cannot See the Request

map_response only receives the response as its last argument, but it can run FromRequestParts extractors such as Path, Query, and HeaderMap before the handler runs. When your middleware needs the request path or headers, add the extractor as an argument. You do not need a different helper for that. What it genuinely cannot do is capture a value from before the handler runs that is not in the request, like a start timestamp.

Mixing Up the Body Types

The body of a Response in Axum is axum::body::Body, which is a struct wrapping a boxed body. When you split a response with into_parts(), you get a Body. When you rebuild with Response::from_parts(parts, body), you must pass a compatible body. To replace the body with a string, convert it with Body::from(string). When you buffer the body with to_bytes, you get Bytes, and you wrap those back into Body::from(bytes).

Buffering Large Responses Without Need

Buffering an entire streaming response just to inspect it can cause high memory use and long delays. When you only need to add a header, do not call to_bytes. Use headers_mut() or into_parts() and leave the body untouched.

Getting the Layer Order Backwards

Response layers run in the order they were added. The first-added layer sees the response first, and the last-added layer sees it last and has the final word. When two layers both change the same header, the one added later wins. Order your .layer() calls with that in mind.

Two layers writing the same header is a silent overwrite:

Nothing warns you when two response layers write the same header. The later one simply replaces the earlier value. When a header ends up with a surprising value, list your layers in the order they were added and check which one runs last on the response path.

Summary

map_response is a focused tool for post-processing responses. It gives you an async function that receives extractors first and a response last, and returns a response or anything implementing IntoResponse. Use headers_mut() for header-only changes, into_parts() when the status must change too, and to_bytes only when the body bytes themselves must change, because buffering defeats streaming.

The decision framework follows from the limits. When the work is purely about the finished response, use map_response. When the change needs a value from the request, add a FromRequestParts extractor. When the change needs shared application state, use the state-aware companion, which takes the state as its first argument. And when the work needs a value captured before the handler runs, such as a start time, use the bracketing form that passes control onward and returns the response, because map_response has no code that runs before the handler.