expression
Axum: state inside middleware
Middleware that extracts State needs from_fn_with_state. Supply a cloneable configuration value when constructing the layer. The example uses an immutable header value and does not store per-request identity. In-memory standalone Cargo example. Expected stdout (not executed): study Common mistake: Using from_fn with State and expecting router state to be passed automatically.
Formal Syntax & Structure
rust syntaxrust
middleware::from_fn_with_state(state, function)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::{extract::State, routing::get, middleware::{self, Next}, response::Response, http::HeaderValue}; #[derive(Clone)] struct Config { label: HeaderValue } async fn mark(State(c): State<Config>, req: axum::extract::Request, next: Next) -> Response { let mut r = next.run(req).await; r.headers_mut().insert("x-label", c.label); r } let c = Config { label: HeaderValue::from_static("study") }; let app = Router::new().route("/", get(|| async { "ok" })).layer(middleware::from_fn_with_state(c, mark)); let r = app.oneshot(Request::new(Body::empty())).await.unwrap(); println!("{}", r.headers()["x-label"].to_str().unwrap());}