with_state in Axum

Learn how to attach shared application state to an Axum router using the with_state method, and understand the type changes and common mistakes that come with it.

When you build a web application, you often have data that many different request handlers need to access. A database connection pool, a configuration struct, a counter for tracking visits, or a cache are all examples. In Axum, the standard way to make such data available to your handlers is to attach it to your router with the with_state method. This page explains exactly what that method does, why it exists, and how to use it without running into the usual beginner errors.

What with_state Does

with_state takes a value that implements the Clone trait and attaches it to the router. Once attached, any handler that uses the State extractor can receive a clone of that value. Behind the scenes, with_state satisfies the state the router was still missing: before the call, a router whose handlers need State<AppState> has type Router<AppState> (still missing its state); after the call, it becomes Router<()>, meaning nothing is missing and the router can be served. That type change is what allows the compiler to know at compile time that your state is available and what type it is.

Think of with_state as placing a shared object into a box that every handler can open. The method moves your value into the router and stores it there, and then each request gets a clone of that object when a handler asks for it with State. Because the object is cloned per request, it must implement Clone. That is why you always derive or implement Clone on your state struct.

A Minimal Example

Let's start with the smallest possible application that uses with_state. You need a state type, at least one handler that extracts it, and a router that attaches the state.

use axum::{
    extract::State,
    routing::get,
    Router,
};
// Our application state. It holds a simple string message.
#[derive(Clone)]
struct AppState {
    message: String,
}
// A handler that reads the state and returns the message.
async fn hello(State(state): State<AppState>) -> String {
    state.message.clone()
}
#[tokio::main]
async fn main() {
    // Create the state.
    let state = AppState {
        message: "Hello from shared state!".to_string(),
    };
    // Build the router, add a route, and attach the state.
    let app = Router::new()
        .route("/", get(hello))
        .with_state(state);
    // Start the server.
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Run this program and visit http://127.0.0.1:3000/ in your browser. You'll see the message Hello from shared state!.

Notice the pattern: Router::new() gives you a router whose state type is decided by the handlers you add. You add a route with .route("/", get(hello)). That route's handler hello expects a State<AppState> extractor, so adding it makes the router a Router<AppState>, a router that is still missing its state. If you tried to serve it now, the compiler would complain. The .with_state(state) call provides that missing state and turns the router back into Router<()>, which is the only form axum::serve accepts. The compiler checks this connection at compile time, which is a huge safety win.

You Have Attached State Correctly:

If your program compiles and you see the message in the browser, your state is attached properly. The key sign that everything is correct is that the router's type is Router<()> (nothing missing) by the time you serve it. You don't see that type in the code, but the compiler uses it to verify your handlers.

How with_state Works Under the Hood

The Router type in Axum is generic over a state type S. When you create a router with Router::new(), S starts out unconstrained, and the compiler works it out from the handlers you add. A handler that needs State<AppState> makes the router a Router<AppState>, which means the router is still missing a state of type AppState. The .route method does not supply that state; it only registers paths and handlers, and the missing state type is inferred from what those handlers ask for.

When you call .with_state(state), two things happen:

  1. The router moves your state value in and stores it internally.
  2. The router's type parameter changes to whatever missing state type the caller picks next, usually (), meaning nothing is missing and the router can be served. with_state does not stamp the state type onto the router; it satisfies the requirement the router had, and the new type is chosen by how the result is used.

Because with_state takes ownership of the value, you cannot use the original state variable afterwards unless you cloned it first. If you need the value again after attaching it, pass .with_state(state.clone()) instead. For types that are cheap to clone (like an Arc), that is fine. For heavy types, wrap them in Arc first so the clone stays cheap.

Different Ways to Call with_state

There are two common positions for .with_state() in a router building chain. Only one of them works with plain axum::serve.

Attach State Last

This is the style used in the minimal example above: create the router, add all routes, then call with_state at the very end.

let app = Router::new()
    .route("/", get(hello))
    .with_state(state);

This is the style you should use. with_state consumes the router and returns a new router whose state type is inferred from how it is used next. When you pass the result to axum::serve, that type is (), so the final router is Router<()>, which is the only router type axum::serve accepts.

Attach State Early

You can also call with_state on an empty router before adding routes, and that code compiles on its own:

let app = Router::new()
    .with_state(state)
    .route("/", get(hello));

But the router you get back is Router<AppState>, not Router<()>, and axum::serve only accepts Router<()>. So if you attach state early and then try to serve the result directly, the compiler rejects it with the trait bound `Router<AppState>: Service<IncomingStream<...>>` is not satisfied. The order matters: call with_state last, after all your routes, so that the router ends up with state type (). If you really need to attach state early, clone the value for the early call and call with_state again at the end with the original, so the final call supplies the state the routes added after the first call are still missing:

let app = Router::new()
    .with_state(state.clone())
    .route("/", get(hello))
    .with_state(state);

This compiles and serves, because the last with_state call leaves the router as Router<()>. The early call is still pointless in most code, so prefer attaching state once, at the end.

You Can Call with_state Twice, But Each Call Keeps Its Own State:

Calling .with_state a second time on the same router compiles: it consumes the router and returns a new one whose remaining missing state type you pick. The first state is not replaced: routes that were already given their state keep working with it, and the second call supplies state for routes added after the first call. In practice, call it exactly once, at the end.

A State Type Without Clone

What happens if you forget to derive Clone? The compiler will reject your code. This is the most common beginner mistake.

use axum::{extract::State, routing::get, Router};
// Missing #[derive(Clone)]
struct AppState {
    message: String,
}
async fn hello(State(state): State<AppState>) -> String {
    state.message.clone()
}
#[tokio::main]
async fn main() {
    let state = AppState {
        message: "Hello".to_string(),
    };
    let app = Router::new()
        .route("/", get(hello))
        .with_state(state); // Error: AppState does not implement Clone
}

The error message will say something like the trait bound AppState: Clone is not satisfied. The with_state method has a requirement that S: Clone. All state types used with with_state must be clonable. This is because Axum gives each handler its own clone of the state for each request.

Forgetting Clone Derive Breaks Compilation:

Without #[derive(Clone)] or a manual Clone implementation, with_state will not compile. Always check that your state struct implements Clone. If your struct contains fields that are not clonable (like a raw file handle), you will need to wrap them in an Arc or find another solution. This is the most frequent error people hit when first using Axum state.

Using with_state with Arc

In real applications, you often share state across many tasks or threads, and you want to avoid cloning large data. The standard pattern is to wrap the state in std::sync::Arc so that clones are cheap pointer copies. Arc itself implements Clone, so you can attach it directly.

use axum::{extract::State, routing::get, Router};
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
    config: String,
}
async fn show_config(State(state): State<Arc<AppState>>) -> String {
    state.config.clone()
}
#[tokio::main]
async fn main() {
    let state = Arc::new(AppState {
        config: "Some configuration".to_string(),
    });
    let app = Router::new()
        .route("/config", get(show_config))
        .with_state(state);
}

Notice that the handler's extractor is State<Arc<AppState>>. The type you put inside State must exactly match the type you passed to with_state. If you attached AppState but the handler expects Arc<AppState>, that is a type mismatch and won't compile. The same goes for the reverse: if you attach Arc<AppState> but the handler expects AppState, it fails. Keep the types aligned.

Passing State to Nested Routers

When you nest routers, the outer router's state is automatically passed to the inner routers. That means you only call with_state once at the top level.

use axum::{extract::State, routing::get, Router};
#[derive(Clone)]
struct AppState {
    app_name: String,
}
async fn index(State(state): State<AppState>) -> String {
    format!("Welcome to {}", state.app_name)
}
async fn health(State(state): State<AppState>) -> String {
    format!("{} is healthy", state.app_name)
}
fn api_routes() -> Router<AppState> {
    Router::new().route("/health", get(health))
}
#[tokio::main]
async fn main() {
    let state = AppState {
        app_name: "MyApp".to_string(),
    };
    let app = Router::new()
        .route("/", get(index))
        .nest("/api", api_routes())
        .with_state(state);
}

The api_routes function returns Router<AppState>, but it doesn't attach state itself. The state is supplied by the parent router when it is nested. This works because nest requires the inner router to have the same state type as the outer router, and the outer router's state type is AppState once its routes are added. You don't need to call with_state again on the inner router.

That same rule is what decides whether a stateless inner router fits. An inner router whose handlers take no state at all still has to match the outer router's state type, so you write its function to return Router<AppState> even though none of its handlers extract state. The compiler works out the state type from the outer router, and the inner routes simply ignore the state. What does not work is declaring the inner router as Router<()> and nesting it into a Router<AppState>: nest takes a Router<S> with the same S as the outer router, so that combination fails with a type mismatch.

Common Mistakes and Misconceptions

Calling with_state Twice

You can call with_state twice on the same router: it compiles, because each call consumes the router and returns a new one. But the second call does not replace the first state for routes that were already added. Routes added before the second call keep the state they were given, and the second call supplies state only for routes added after it. So a router built as route("/a", ...).with_state(a).route("/b", ...).with_state(b) serves /a with state a and /b with state b, and both routes answer normally. If you need to attach additional state, the clean approach is still to combine your state into a single struct and attach that one struct, because two different state types on one router is hard to read and easy to get wrong.

One Router, One State:

In practice, one router uses one state type. If you have multiple different pieces of data, combine them into one AppState struct. The FromRef trait allows extracting substates from a larger state, but that is a separate topic. For now, remember that with_state is called exactly once in practice, at the end.

Type Mismatch Between Attached State and Extractor

The most subtle error is when the type you pass to with_state does not match what your handler expects in State. The compiler will often give an error about the handler not matching the router's state type. For example:

use axum::{extract::State, routing::get, Router};
#[derive(Clone)]
struct AppState {
    message: String,
}
async fn handler(State(state): State<String>) -> String {
    state
}
#[tokio::main]
async fn main() {
    let state = AppState {
        message: "hello".to_string(),
    };
    let app = Router::new()
        .route("/", get(handler))
        .with_state(state); // Error: expected String, found AppState
}

This fails because handler wants State<String> but we attached AppState. The error message will point to the .with_state(state) call and explain the mismatch. The fix is to make the handler extract the same type that was attached.

Forgetting to Use State Extractor

If you attach state but no handler uses it, that is fine; the state just sits unused, and the program still compiles. The mistake that actually bites is the reverse: a handler that needs the state but forgets to declare the State extractor. That handler also compiles, because nothing forces a handler to take state, but it has no way to reach the shared data. For instance:

async fn handler() -> String {
    "I don't need state".to_string()
}
// Attaching state to a router with this handler is fine,
// but this handler can never read the state.

There is no compiler error to catch this one. You notice it when the handler cannot access a value it was supposed to use. The fix is to add the extractor to the signature: async fn handler(State(state): State<AppState>) -> String.

A Complete Working Example with a Counter

Let's look at a more realistic example that uses a simple in‑memory counter as shared state. This state will be mutated, so we need a Mutex to allow safe concurrent access. Don't worry if you're not familiar with Mutex; for now, just note that it lets multiple requests safely update a number.

use axum::{extract::State, routing::get, Router};
use std::sync::{Arc, Mutex};
#[derive(Clone)]
struct AppState {
    counter: Arc<Mutex<u32>>,
}
async fn increment(State(state): State<AppState>) -> String {
    let mut count = state.counter.lock().unwrap();
    *count += 1;
    format!("Counter is now {}", *count)
}
async fn get_count(State(state): State<AppState>) -> String {
    let count = state.counter.lock().unwrap();
    format!("Counter value: {}", *count)
}
#[tokio::main]
async fn main() {
    let state = AppState {
        counter: Arc::new(Mutex::new(0)),
    };
    let app = Router::new()
        .route("/increment", get(increment))
        .route("/count", get(get_count))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Visit http://127.0.0.1:3000/increment a few times, then visit http://127.0.0.1:3000/count. The counter increases each time. This demonstrates that the same state is shared across all requests: the router stores the state value, and each handler receives a clone of it, but the clone shares the same underlying Mutex through the Arc field, so every increment is visible to the next request.

Why Arc and Mutex?:

In Axum, state must be Clone. Arc is a clonable smart pointer that shares ownership across threads. Inside the Arc, we place a Mutex to allow safe mutation. Without the Mutex, two requests trying to increment the counter at the same time could cause a data race. This pattern is so common that it will appear in many Axum applications.

When Not to Use with_state

with_state is the primary way to share read‑only or synchronized data with handlers. However, there are alternatives for different situations:

  • Request extensions: If you need to attach data to a single request (like user information after authentication), you would use request extensions, not with_state. Extensions are per‑request, not shared across requests.
  • Task‑local variables: For per‑task data that is not part of the request/response cycle, task‑locals can be used, but they are less common and more advanced.
  • Global statics: You can use static variables with OnceLock or lazy_static for data that never changes and is available throughout the program, but that bypasses Axum's dependency injection and is harder to test.

In most cases, if you need shared application data available to handlers, with_state is the right tool.

Summary

The rule that ties this page together is about reading the router's type as a to-do list, not a label. Router<AppState> means the router is still missing a state of type AppState, and with_state crosses that item off by storing the value and returning a router whose remaining missing state is decided by whatever comes next. When the chain ends at axum::serve, that remaining state is (), nothing missing, which is the only form serve accepts. That single reading explains the three mistakes on this page: a missing Clone fails because the stored value must be cloned per request, a mismatched State type fails because the stored value is not the type the handler asked for, and an early with_state fails because the routes added after it open a new missing-state item that nobody crossed off. If you attach state once, at the end, with exactly the type your handlers extract, the type system has nothing left to complain about.