fromfnwith_state - Middleware With Application State in Axum

Learn how to write Axum middleware that reads shared application state with from_fn_with_state, including counters, configuration, and authentication

Middleware often needs more than the request itself. A logging middleware wants the name of the environment the server runs in. An auth middleware wants the secret used to check tokens. A counter wants the number it has counted so far. None of that data lives in the request. It lives in the application, and Axum calls it application state. middleware::from_fn cannot reach that state. middleware::from_fn_with_state is the same idea with state added, and it is the function to reach for whenever middleware needs shared data.

The Shape of a State Aware Middleware Function

A state aware middleware function takes three parameters instead of two. The first is State<S>, where S is the type of the application state. The second is the Request. The third is Next. The State extractor is the same one handlers use, and it gives the function an owned copy of the state value. Owned means the function receives the value itself, not a reference to it, so it can move fields out of it and keep them.

The function that builds the layer has this signature in Axum 0.8.

pub fn from_fn_with_state<F, S, T>(state: S, f: F) -> FromFnLayer<F, S, T>

Read it from left to right. The generic letters are F for the middleware function, S for the state type, and T for the future the function returns. The function takes the state value first and the middleware function second, and it returns a layer. The state type must implement Clone, Send, Sync, and 'static. Clone lets Axum copy the state wherever a copy is needed. Send and Sync let the state move safely between the threads the server runs on. 'static means the state holds no borrowed references that could outlive the data they point at. A plain struct with owned fields and a Clone derive satisfies all four without extra work.

Think of the state as a shared notebook the whole application reads from. The router keeps the original notebook. Each middleware layer and each handler gets a copy of it. When the notebook holds a plain value such as a string, each copy is independent. When it holds a shared pointer such as an Arc, every copy points at the same underlying data, so a change made through one copy is visible through the others. That difference decides how counters and pools are stored, and it comes up later on this page.

The Smallest Example That Uses State

Start with a state struct that holds one string, and a middleware function that prints it before running the handler. Create a project with the dependencies below. The file Cargo.toml sits at the root of the project, and src/main.rs holds the code.

Cargo.toml
[package]
name = "from-fn-with-state-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
src/main.rs
use axum::{
    extract::{Request, State},
    middleware::{self, Next},
    response::Response,
    routing::get,
    Router,
};

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

async fn print_message(State(state): State<AppState>, request: Request, next: Next) -> Response {
    println!("Middleware message: {}", state.message);
    next.run(request).await
}

#[tokio::main]
async fn main() {
    let state = AppState {
        message: "Hello from state!".to_string(),
    };
    let app = Router::new()
        .route("/", get(|| async { "Home page" }))
        .layer(middleware::from_fn_with_state(state.clone(), print_message))
        .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 it with cargo run and open http://127.0.0.1:3000/. The terminal shows the message line before the handler answers.

Middleware message: Hello from state!

Three things are new compared with the plain form. The state struct AppState derives Clone, which the layer requires. The middleware function takes State<AppState> as its first parameter, and the pattern State(state) unwraps the value out of the extractor. The layer is built with middleware::from_fn_with_state(state.clone(), print_message), which takes the state value and the function. The state.clone() is needed because the same value is passed again to .with_state(state) on the next line, and Rust does not let one value be moved twice. Cloning gives the layer its own copy and leaves the original for the router.

The message line means state reached the middleware:

If the terminal shows the middleware message when a request arrives, the state travelled from main into the middleware function. If the message never appears, check that the layer was built with from_fn_with_state and not with the plain from_fn, which cannot take a State parameter.

Building a State Aware Middleware in Three Steps

The work always follows the same order. First define the state type and create a value of it. Then write the middleware function that takes State<S> first. Then apply the layer with the state value and register the same state on the router. Each step depends on the one before it, because the function cannot be written until the state type exists, and the layer cannot be built until both exist.

1

Step 1: Define the shared state type

Decide what data the middleware needs and put it in a struct that derives Clone. The struct below holds a request counter and a service name.

use std::sync::{Arc, Mutex};

#[derive(Clone)]
struct AppState {
    request_count: Arc<Mutex<u64>>,
    service_name: String,
}
2

Step 2: Write the middleware function

Write an async function that takes State<AppState> first, then Request and Next. The function reads the state, uses it, and passes the request onward.

async fn track_requests(
    State(state): State<AppState>,
    request: Request,
    next: Next,
) -> Response {
    let mut count = state.request_count.lock().unwrap();
    *count += 1;
    println!("{} has handled {} requests", state.service_name, *count);
    drop(count);
    next.run(request).await
}
3

Step 3: Create the state and apply the middleware

In main, create the state, apply the middleware with from_fn_with_state, and register the state on the router with .with_state.

let state = AppState {
    request_count: Arc::new(Mutex::new(0)),
    service_name: "user-service".to_string(),
};
let app = Router::new()
    .route("/", get(|| async { "Hello" }))
    .layer(middleware::from_fn_with_state(state.clone(), track_requests))
    .with_state(state);

The drop(count) line in step 2 releases the lock before next.run is awaited. That matters, because a standard library mutex guard cannot be held across an await, and the counter example below shows the same scoping in full.

Why the State Appears in Two Places

The example passes the state twice, once to from_fn_with_state and once to .with_state. Those two calls do different jobs. from_fn_with_state(state.clone(), f) gives state to that one middleware layer, and the layer keeps its own copy. .with_state(state) registers the state on the router, which makes it available to handlers that take State<AppState> and to any other layer that expects it. The layer works from its own copy either way, so a middleware layer with its own state runs even when the router never calls .with_state.

That split has a sharp edge. When a handler takes State<AppState> but the router never called .with_state, the program fails to compile at the axum::serve call with an error about the router not implementing the service trait. The compiler message names the missing trait bound rather than saying the state is missing, which makes it hard to read. When no handler uses State, the same program compiles and runs, because nothing asks the router for state. So the rule is practical rather than absolute. Call .with_state whenever any handler on the router reads state, and the error never appears.

A missing with_state fails at serve time, not at the router:

If a handler uses State<AppState> and the router has no .with_state, the failure appears at the axum::serve call, not where the router is built. The error mentions a trait bound on the router. The fix is one line, adding .with_state(state) after the layers. Always add it when a handler reads state.

State Gives an Owned Value, Not a Reference

State<S> hands the middleware an owned S, a full copy of the stored value, not a shared reference to it. That is easy to miss, because the word "shared" suggests borrowing. The proof is that the middleware can move a field out of the state. The function below takes the message string out of AppState by value, which would be impossible if state were only a reference.

async fn owned_state(State(state): State<AppState>, request: Request, next: Next) -> Response {
    let msg: String = state.message;
    println!("owned: {}", msg);
    next.run(request).await
}

This function compiles and runs, and it prints owned: owned! when the state holds that string. Each request gets a fresh clone of the stored state, so moving a field out affects only that request's copy. The consequence is that a plain field such as a String or a u64 cannot be used as shared mutable data, because each clone is independent. When the data must be shared and changeable, the state struct holds a shared pointer to it instead, which is what the counter example does next.

Sharing Mutable State With Arc and Mutex

A request counter must be shared across requests and must change. A plain u64 field cannot do that, because each request gets its own clone. The standard pattern wraps the mutable value in an Arc<Mutex<T>>. Arc is an atomic reference counted pointer, a smart pointer that lets many owners share one value, and cloning it is cheap because it only copies the pointer. Mutex is a lock that lets only one thread touch the value at a time. Together they give every clone of the state access to the same counter.

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

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

async fn count_requests(
    State(state): State<AppState>,
    request: Request,
    next: Next,
) -> Response {
    {
        let mut counter = state.counter.lock().unwrap();
        *counter += 1;
        println!("Request number: {}", *counter);
    }
    next.run(request).await
}

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

Two requests to / print Request number: 1 and then Request number: 2, because both clones of the state point at the same counter through the Arc. The lock is held only inside the small block, and it is released before next.run is awaited. That scoping is deliberate. The guard returned by a standard library Mutex is not Send across an await point, which means holding it while awaiting next.run makes the whole future unusable on a multi-threaded server, and the compiler rejects the program. Releasing the lock before the await avoids the problem entirely, and it also keeps the counter from blocking other requests while the handler runs.

Do not hold a standard Mutex guard across an await:

Holding a std::sync::MutexGuard while calling next.run(request).await fails to compile, because the guard cannot be sent between threads. Lock, change the value, and drop the guard before the await. The block scope in the example does exactly that.

When the lock genuinely must be held across the whole request, for example to process requests one at a time, use the async mutex from Tokio instead. tokio::sync::Mutex is built for async code, and its guard can be held across an await.

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

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

async fn serialize_requests(
    State(state): State<AppState>,
    request: Request,
    next: Next,
) -> Response {
    let mut counter = state.counter.lock().await;
    *counter += 1;
    println!("Request number {} started", *counter);
    let response = next.run(request).await;
    println!("Request number {} finished", *counter);
    response
}

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

This compiles and runs, and the counter is held for the whole request, so requests are processed one at a time. That serialises the server, which is slow, so use it only when the work truly cannot overlap. For most counters and pools, the short lock from the previous example is the right shape. The same thinking applies to large state. When the state holds a big configuration object, store it behind an Arc inside the struct, so cloning the state copies a pointer instead of the whole object.

Stacking Two Middleware and the Order They Run In

Several state aware middleware layers can be stacked. The example below stacks a plain logging middleware and a state aware timing middleware, and the order they run in follows one rule, the last .layer call runs first. A live run of this exact stacking printed the elapsed time line first and the method line second, because measure_time was added last and runs before log_method.

src/main.rs
use axum::{
    extract::{Request, State},
    middleware::{self, Next},
    response::Response,
    routing::get,
    Router,
};
use std::time::Instant;

#[derive(Clone)]
struct AppState {
    start_time: Instant,
}

async fn log_method(request: Request, next: Next) -> Response {
    let method = request.method().to_string();
    println!("Method: {}", method);
    next.run(request).await
}

async fn measure_time(State(state): State<AppState>, request: Request, next: Next) -> Response {
    let elapsed = state.start_time.elapsed();
    println!("Server has been running for {:?}", elapsed);
    let response = next.run(request).await;
    let after = state.start_time.elapsed();
    println!("Request completed after {:?}", after);
    response
}

#[tokio::main]
async fn main() {
    let state = AppState {
        start_time: Instant::now(),
    };
    let app = Router::new()
        .route("/", get(|| async { "OK" }))
        .layer(middleware::from_fn(log_method))
        .layer(middleware::from_fn_with_state(state.clone(), measure_time))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

When two middleware depend on each other, for example when one reads a value another one sets, test the order with prints before trusting it.

Authentication Middleware That Reads a Secret From State

The most common real use of state aware middleware is authentication. The secret used to check tokens is configuration, so it belongs in state rather than hard coded in the middleware function. The example below keeps a secret in state, compares the authorization header against it, and returns 401 for anything else.

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

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

async fn require_auth(
    State(state): State<AppState>,
    request: Request,
    next: Next,
) -> Response {
    let authorized = request
        .headers()
        .get("authorization")
        .and_then(|value| value.to_str().ok())
        .map(|value| value == format!("Bearer {}", state.jwt_secret))
        .unwrap_or(false);
    if authorized {
        next.run(request).await
    } else {
        StatusCode::UNAUTHORIZED.into_response()
    }
}

async fn protected_handler() -> &'static str {
    "This is protected data"
}

#[tokio::main]
async fn main() {
    let state = AppState {
        jwt_secret: "my-secret-token".to_string(),
    };
    let app = Router::new()
        .route("/protected", get(protected_handler))
        .layer(middleware::from_fn_with_state(state.clone(), require_auth))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request without the header gets a 401. A request with authorization: Bearer my-secret-token gets a 200 and the protected text. The secret is read from state on every request, so changing the state value at startup changes what the middleware accepts, and the middleware function itself never mentions the secret. In a real application the comparison would check a signed token against the secret rather than comparing strings directly, but the shape is the same. The state holds the configuration, the middleware reads it, and the handler only runs when the check passes.

Two Middleware With Different State Values

Each layer built by from_fn_with_state carries its own state value, independent of the router and independent of the other layers. That means two middleware functions can use two different state types. The example below gives a logging middleware a LoggingState and an auth middleware an AuthState, each through its own from_fn_with_state call.

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

#[derive(Clone)]
struct LoggingState {
    log_level: String,
}

#[derive(Clone)]
struct AuthState {
    jwt_secret: String,
}

async fn logging_mw(State(state): State<LoggingState>, req: Request, next: Next) -> Response {
    println!("level {}", state.log_level);
    next.run(req).await
}

async fn auth_mw(State(state): State<AuthState>, req: Request, next: Next) -> Response {
    println!("secret length {}", state.jwt_secret.len());
    next.run(req).await
}

#[tokio::main]
async fn main() {
    let logging_state = LoggingState {
        log_level: "debug".to_string(),
    };
    let auth_state = AuthState {
        jwt_secret: "secret".to_string(),
    };
    let app = Router::new()
        .route("/", get(|| async { "ok" }))
        .layer(middleware::from_fn_with_state(
            logging_state.clone(),
            logging_mw,
        ))
        .layer(middleware::from_fn_with_state(auth_state.clone(), auth_mw))
        .with_state(logging_state)
        .with_state(auth_state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request prints secret length 6 first and then level debug, because the auth layer was added last and runs first. Both layers work, and the handler answers with a 200. Two things are worth noticing. The two .with_state calls both compile, and each layer still gets its own state from its own from_fn_with_state call. But a handler cannot take two different State types at once. A handler that declares both State<LoggingState> and State<AuthState> fails to compile, because the router carries one state type for handlers. That is why the usual shape is a single AppState struct holding everything the handlers need, while separate small state types are fine for middleware layers that each need only one piece.

One struct for handlers, small pieces for layers:

Handlers read state through one State<AppState> type, so put everything handlers need into a single struct. Middleware layers are different, because each from_fn_with_state call carries its own value, so a layer can use a small dedicated state type. Mixing the two shapes is fine as long as the handler side stays on one struct.

Combining State Aware Middleware With Other Layers

from_fn_with_state returns an ordinary tower layer, so it combines with any other layer, including the tracing layer from tower-http. The ordering rule still applies. In the example below the tracing layer is added after the state aware logging middleware, so the tracing layer is outermost and runs first for each request.

src/main.rs
use axum::{
    extract::{Request, State},
    middleware::{self, Next},
    response::Response,
    routing::get,
    Router,
};
use tower_http::trace::TraceLayer;

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

async fn log_app_name(State(state): State<AppState>, request: Request, next: Next) -> Response {
    println!("Serving request for {}", state.app_name);
    next.run(request).await
}

#[tokio::main]
async fn main() {
    let state = AppState {
        app_name: "MyAxumApp".to_string(),
    };
    let app = Router::new()
        .route("/", get(|| async { "Hello" }))
        .layer(middleware::from_fn_with_state(state.clone(), log_app_name))
        .layer(TraceLayer::new_for_http())
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The Cargo.toml for this example adds tower-http with the trace feature.

Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower-http = { version = "0.7", features = ["trace"] }

A request prints the app name line from the custom middleware. The tracing layer itself stays silent in this example, because no tracing subscriber is set up to receive its events, so the only visible output is the app name line. The point of the example is the combination, not the logs. The state aware middleware does not care what the other layer is. It reads its state, does its work, and passes the request onward. That is the whole point of the layer shape. Each layer is independent, and the order they are added decides the order they run in.

Common Mistakes and How to Fix Them

The first mistake is using the plain from_fn with a function that takes a State parameter. The compiler rejects it with a trait error on the .layer call, because from_fn does not support extracting state. Switch the call to from_fn_with_state and pass the state value as the first argument.

The second mistake is forgetting the Clone derive on the state struct. The layer needs to clone the state, so the compiler reports that the state type does not implement Clone. Adding #[derive(Clone)] fixes it, and any field that cannot be cloned, such as a database pool handle, usually needs to sit behind an Arc.

The third mistake is passing the state value twice without cloning. The value moves into the first call, so the second call fails with a use-after-move error. Clone it for the layer and pass the original to .with_state, or clone it for .with_state and pass the original to the layer. Either order works.

The fourth mistake is forgetting .with_state when a handler reads state. The program fails at axum::serve with a trait bound error, as described earlier. The fix is the one line that registers the state on the router.

The fifth mistake is holding a standard library mutex guard across an await. The compiler rejects the future as not safe to send between threads. Release the lock before the await, or switch to the Tokio mutex when the lock must be held across it.

The state type must match in every place:

The state type appears in three places, the struct, the State<AppState> parameter in the middleware function, and the .with_state argument. If any one of them names a different type, the compiler reports a trait bound failure at the router or at the serve call. Check all three when the error points at the router setup rather than at a line of your own logic.

Summary

The decision inside this topic is small and practical. When middleware needs nothing but the request, the plain form is enough, and adding state would only add noise. When middleware needs configuration, a pool, a counter, or any value that lives longer than one request, the stateful form is the answer, and the shape is always the same. Define a Clone struct, take State<S> first in the function, pass a clone of the value to from_fn_with_state, and register the value on the router with .with_state. The two rules that save the most debugging time are the ones this page verified directly. State arrives as an owned clone, so shared mutable data must sit behind an Arc, and a standard mutex guard must be dropped before any await. With those two rules in hand, state aware middleware behaves like any other middleware, only with the application's own data in reach.