expression

Axum: request-local typed extensions

Extensions carry typed metadata alongside one request. A middleware can compute information once and make it available to downstream handlers. The example inserts a synthetic label rather than a user identity. In-memory standalone Cargo example. Expected stdout (not executed): demo Common mistake: Storing request-local data in a global mutable variable.

Formal Syntax & Structure

rust syntaxrust
req.extensions_mut().insert(value); Extension(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::{Extension, routing::get, middleware::{self, Next}, response::Response};    #[derive(Clone)] struct Label(&'static str);    async fn label(mut req: axum::extract::Request, next: Next) -> Response {        req.extensions_mut().insert(Label("demo"));        next.run(req).await    }    async fn show(Extension(label): Extension<Label>) -> &'static str { label.0 }    let app = Router::new().route("/", get(show)).layer(middleware::from_fn(label));    let r = app.oneshot(Request::new(Body::empty())).await.unwrap();    println!("{}", std::str::from_utf8(&to_bytes(r.into_body(), 32).await.unwrap()).unwrap());}
Rust Reference