expression

Axum: add a response header in middleware

A response can be modified on its way back to the caller. A shared middleware can supply a consistent response header while preserving the original status and body. In-memory standalone Cargo example. Expected stdout (not executed): 1 Common mistake: Changing the request header when the intended recipient is the response client.

Formal Syntax & Structure

rust syntaxrust
response.headers_mut().insert(name, value)

Working Example

Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() {    use axum::{routing::get, middleware::{self, Next}, response::Response, http::HeaderValue};    async fn decorate(req: axum::extract::Request, next: Next) -> Response {        let mut r = next.run(req).await;        r.headers_mut().insert("x-demo-version", HeaderValue::from_static("1"));        r    }    let app = Router::new().route("/", get(|| async { "ok" })).layer(middleware::from_fn(decorate));    let r = app.oneshot(Request::new(Body::empty())).await.unwrap();    println!("{}", r.headers()["x-demo-version"].to_str().unwrap());}
Rust Reference