Understanding the Router Type Parameter in Axum

Learn what the generic type parameter on Axum's Router means, why it exists, how it works, and how to use it correctly when adding shared state to your application.

When you create an Axum application, the Router type is not just a simple struct. It carries a generic type parameter that often appears in compiler messages and type signatures. This parameter is crucial for building type-safe web applications in Axum, and understanding it will prevent many frustrating compiler errors.

What Is the Router Type Parameter?

In Axum, Router is defined as Router<S>. The S stands for state - but it means the state the router is still missing, not the state it already holds. A router whose handlers need State<AppState> has type Router<AppState> until you provide that state; once you do, it becomes Router<()>, meaning "no state missing", and only then can it be served.

Think of Router<S> as a checklist: the type parameter says what kind of shared data the router still needs before it is complete. If the checklist says Router<()>, nothing is missing and the router is ready. If it says Router<AppState>, the router still needs an AppState before it can run.

Here is a simple mental model: Router is like a box with a label. The label says what you still have to put in the box. If the box says Router<()>, the box is complete and needs nothing more. If the box says Router<AppState>, you still owe it an AppState for all your handlers to share - you supply it with .with_state(...), and the label then reads Router<()>.

Starting with the Default: Router<()>

Let's begin with the most basic Axum application. You have already seen how to create a router and add routes, but now we focus on the type parameter.

use axum::{Router, routing::get};
async fn hello_world() -> &'static str {
    "Hello, World!"
}
fn main() {
    let app: Router<()> = Router::new()
        .route("/", get(hello_world));
    // The type of `app` is `Router<()>`.
    // We could also write it explicitly:
    // let app: Router<()> = Router::new().route("/", get(hello_world));
    println!("Router created successfully");
}

In this code, Router::new() creates a router with the default state type (). The route method does not change that type; it only adds routes. So app is of type Router<()>. This is the simplest possible router, and it works because none of your handlers need to access shared state.

The Router<()> annotation on let app is not decoration. The compiler cannot always work out the finished type of a router on its own when the router is never served in the same function, so writing the type out removes the guesswork. Whenever a router is passed to axum::serve, serving pins the type to Router<()> automatically and the annotation is optional - but writing it never hurts, and it makes the type visible while you are learning.

If you ever see the compiler mention Router<()> when you didn't explicitly write it, that just means you have a stateless router. It is completely normal and often what you want for small examples or truly stateless services.

Adding State Changes the Type Parameter

Real web applications usually need some shared data: a database connection pool, configuration values, a cache, or any resource that multiple handlers must use. Axum calls this shared data state.

A handler that extracts State<AppState> makes its router a Router<AppState> - a router that is still missing an AppState. You supply it with .with_state(...), and the router becomes Router<()> (ready to serve). So .with_state(...) does not change the type to AppState; it satisfies the AppState requirement and removes it from the type.

Here is a concrete example. We define a simple struct to hold application state, then attach an instance of it to the router.

use axum::{Router, routing::get};
#[derive(Clone)]
struct AppState {
    app_name: String,
}
async fn hello_world() -> &'static str {
    "Hello, World!"
}
fn main() {
    let state = AppState {
        app_name: "My Axum App".to_string(),
    };
    let app: Router<()> = Router::new()
        .route("/", get(hello_world))
        .with_state(state);
    // The route's handler uses no state, so nothing here needs the
    // `AppState` value. `.with_state(state)` still accepts it and
    // stores it, and `app` ends up as `Router<()>` - ready to serve.
    // (The stored state only reaches routes that were added before this
    // call and need it; a stateful route added afterwards needs the
    // router to be `Router<AppState>` first.)
}

Notice what happened: Router::new() starts as Router<()>, and because hello_world does not use state, it stays Router<()>. If the handler did use State<AppState>, the router would be Router<AppState> before .with_state(...), and .with_state(state) would satisfy that requirement, turning it back into Router<()> - the type a router must have before it can be served. The Router<()> annotation on let app is there for the same reason as in the previous example: this function never serves the router, so the compiler needs the finished type written out. In a real program you would pass app to axum::serve, which pins the type to Router<()> on its own.

Why does the type parameter exist at all? Because Rust is statically typed. The compiler wants to guarantee that any handler that tries to use state does so correctly. By keeping track of the state type in the Router type, Axum can enforce at compile time that your handlers and your router agree on the state type.

Why the Type Parameter Exists: Compile-Time Safety

Imagine you have a handler that expects access to AppState:

use axum::{
    Router,
    routing::get,
    extract::State,
};
#[derive(Clone)]
struct AppState {
    app_name: String,
}
async fn hello_world(State(state): State<AppState>) -> String {
    format!("Hello from {}", state.app_name)
}

This handler uses the State extractor to receive the shared AppState. It will only work if the router that serves this handler is given an AppState before serving.

If you try to serve a router whose handlers need State<AppState> without calling .with_state(...), you will get a compile error. Adding the handler changed the router's type to Router<AppState> - a router that is still missing its state - and a router with missing state cannot be turned into a running service. Only Router<()> (nothing missing) can be served. The type system prevents you from running a program where a handler requests state that doesn't exist.

Let's see the error in code (we'll just show the incorrect code and describe the error because actually compiling it would fail):

// This code will NOT compile.
use axum::{Router, routing::get, extract::State};
#[derive(Clone)]
struct AppState {
    app_name: String,
}
async fn hello_world(State(state): State<AppState>) -> String {
    format!("Hello from {}", state.app_name)
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(hello_world));
    // ERROR: `app` is `Router<AppState>` (still missing its state),
    // but serving requires `Router<()>` (nothing missing).
    // The compiler reports that the `Service` trait is not implemented
    // for `Router<AppState>`. Fix it by adding
    // `.with_state(AppState { ... })` before serving.
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The error message will say something about the router not implementing the service trait for the missing state type. The key point is that the type parameter makes this mismatch visible at compile time rather than causing a runtime panic when a request arrives and the state is missing.

This is the core benefit: the Router type parameter ties the state type to the router itself, ensuring that every handler that needs state gets the correct type, and no handler can accidentally run without it.

How the Type Parameter Flows Through Methods

Most methods on Router preserve or modify the state type parameter in predictable ways. Remember: the parameter names the state the router is still missing.

  • Router::new() → Router<()> (nothing missing yet)
  • .route(path, method_router) → the router's missing state becomes whatever its handlers need. Adding a route whose handler uses State<AppState> to a Router<()> turns it into Router<AppState>; adding a stateless route changes nothing.
  • .with_state(state) → provides the state the router is currently missing and returns Router<()>, ready to serve. (You can also ask for a different next-missing type, but Router<()> is the usual result.)
  • .merge(other_router) → requires both routers to be missing the same state type S (or have their state provided first with .with_state(...))
  • .nest(path, other_router) → also requires matching missing state types, unless the nested router already had its state provided with .with_state(...) first.

Understanding this flow helps you reason about what type your router currently has and what you need to do to add features.

A common pattern is to build a router with routes that need state, and then call .with_state(...) at the end. That way, you don't have to worry about carrying the state value while constructing the router.

use axum::{Router, routing::get, extract::State};
#[derive(Clone)]
struct AppState {
    app_name: String,
}
async fn hello_world(State(state): State<AppState>) -> String {
    format!("Hello from {}", state.app_name)
}
fn main() {
    // Create the router with a route that expects state.
    // Because the handler uses `State<AppState>`, this router is
    // `Router<AppState>` - it is still missing its state.
    let app: Router<()> = Router::new()
        .route("/", get(hello_world))
        // Now provide the state, turning `Router<AppState>` into `Router<()>`.
        .with_state(AppState {
            app_name: "My Axum App".to_string(),
        });
    // `app` is `Router<()>`, ready to serve.
    // (The annotation is needed here because this function never serves
    // the router, so the compiler cannot pin the finished type itself.)
}

Notice the annotation on let app. Without it, the compiler cannot pin the finished type, because this function never serves the router. In a program that does serve the router, the annotation is optional - passing the router to axum::serve pins the type to Router<()> on its own. Either way, the type ends up as Router<()> once the state is provided.

A Full Example: From Stateless to Stateful

Let's build a complete, runnable Axum application that demonstrates the Router type parameter in action. This example will show a stateless version first, then convert it to a stateful one.

Step 1: A Simple Stateless Router

Create a new Axum project (if you haven't already) and write this code in main.rs:

use axum::{Router, routing::get};
async fn hello() -> &'static str {
    "Hello, no state here!"
}
#[tokio::main]
async fn main() {
    let app: Router<()> = Router::new()
        .route("/", get(hello));
    println!("Router type: {}", std::any::type_name_of_val(&app));
    // This will print: axum::routing::Router
    // (`()` is the default type parameter, so it is omitted from the printed name.)
    // Normally you would serve the app with `axum::serve(listener, app)`, but here we just show the type.
    // (The `Router<()>` annotation is needed because the router is never
    // served here, so the compiler cannot pin its type on its own.)
}

Run this program. It will print the type name, confirming it is Router<()>.

Step 2: Add a State Struct and a Handler That Uses It

Now add a state struct and a handler that extracts it. We also need to call .with_state(...).

use axum::{Router, routing::get, extract::State};
#[derive(Clone)]
struct AppState {
    message: String,
}
async fn hello(State(state): State<AppState>) -> String {
    format!("Message from state: {}", state.message)
}
#[tokio::main]
async fn main() {
    let state = AppState {
        message: "Hello, with state!".to_string(),
    };
    let app: Router<()> = Router::new()
        .route("/", get(hello))
        .with_state(state);
    println!("Router type: {}", std::any::type_name_of_val(&app));
    // This will print: axum::routing::Router
    // The router is `Router<()>` now: `.with_state(state)` satisfied the
    // `AppState` requirement. (Before `.with_state(...)`, the same router
    // would have printed as `axum::routing::Router<...AppState>`.)
    // (The `Router<()>` annotation is needed because the router is never
    // served here, so the compiler cannot pin its finished type on its own.)
}

When you run this, the type name will show axum::routing::Router - the router is Router<()> once .with_state(state) has satisfied the AppState requirement. The .with_state(state) call provides the state the routes were missing.

This is the fundamental pattern: build routes that expect state, then provide the state once at the end.

Common Misconceptions and Mistakes

Mistake 1: Forgetting to Call .with_state When a Handler Uses State<T>

This is the most common error. You write a handler that extracts State<AppState>, but you forget to add .with_state(...) to the router. The compiler will fail with a type mismatch. Always ensure that any route that uses State<T> is placed on a router that eventually gets .with_state(...) with a matching type.

Mismatched State Type:

If you call .with_state(state) but the state type does not match what the handler expects (e.g., you pass OtherState but the handler expects AppState), the compiler will also produce a type error. The state type must match exactly, including all fields and their types.

Mistake 2: Trying to Use Multiple Different State Types

You cannot easily have a router that holds two different state types. The Router<S> has only one type parameter. If you need multiple pieces of shared data, you should combine them into a single struct. For example:

#[derive(Clone)]
struct AppState {
    db_pool: DbPool,
    config: Config,
}

Here DbPool and Config stand in for whatever types your own application actually shares - a database pool type and a configuration type, for instance. The point is the shape, not the names: one struct holds every piece of shared data, so the router has exactly one state type to track. Then your handlers can extract State<AppState> and access both fields.

Mistake 3: Calling .with_state with the wrong type

.with_state(state) must provide exactly the state type the router is currently missing. If the router's routes need State<AppState> and you pass an OtherState, the compiler will reject it with a type mismatch - the argument has to be the missing type, not just any state. The fix is to pass the type the handlers actually expect.

Note that you can call .with_state more than once, as long as each call provides what the router is missing at that point. The order matters: add the routes that need the first state, satisfy them, then add the routes that need the second state, and satisfy those. Each call turns the router back into Router<()>, ready for the next batch of routes:

use axum::{Router, routing::get, extract::State};
#[derive(Clone)]
struct AppStateA {
    a: String,
}
#[derive(Clone)]
struct AppStateB {
    b: String,
}
async fn handler_a(State(state): State<AppStateA>) -> String {
    state.a.clone()
}
async fn handler_b(State(state): State<AppStateB>) -> String {
    state.b.clone()
}
fn main() {
    let app: Router<()> = Router::new()
        // The `/a` route needs `State<AppStateA>`, so the router is
        // `Router<AppStateA>` here. This call satisfies that requirement.
        .route("/a", get(handler_a))
        .with_state(AppStateA { a: "a".to_string() })
        // Now the router is `Router<()>` again, so adding a route that
        // needs `State<AppStateB>` turns it into `Router<AppStateB>`,
        // and the second call satisfies that requirement.
        .route("/b", get(handler_b))
        .with_state(AppStateB { b: "b".to_string() });
    // `app` is `Router<()>`, ready to serve.
}

What does not work is passing a type no route needs, calling .with_state with the second state before any route needs it, or forgetting a .with_state call for a newly added stateful route before serving.

Mistake 4: Not Deriving Clone on the State Type

Axum requires the state type to implement Clone. This is because the router may need to share the state across many connections and tasks. If you forget #[derive(Clone)] on your state struct, you will get a compile error when calling .with_state. Many beginners miss this.

State Must Be Cloneable:

Axum's state is shared by reference via the State extractor, but the router itself needs to clone the state for internal reasons. Always derive Clone for your state types. If your state contains a type that cannot be cloned (like a raw database connection), wrap it in an Arc (e.g., Arc<Mutex<...>> or Arc<Pool>).

Mistake 5: Confusing the State Type Parameter with the Request or Response Types

The S in Router<S> only concerns the application state, not the request or response body types. In Axum 0.8, Router has no body type parameter at all - there is no Router<S, B>. In typical usage, you only need to care about S.

Two Ways to Create a Stateful Router: Explicit Type Annotation vs Inference

You can either let Rust infer the state type or annotate it explicitly. Both are valid, but they suit different situations.

Approach 1: Let Inference Do the Work

The simplest way is to build the router and call .with_state(...) at the end. The compiler will infer the final type. This is what we've done in previous examples.

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

Approach 2: Annotate the Router Type

Sometimes you might want to define a function that returns a router, or store the router in a struct, and you need to specify the type. You can write the full type annotation.

fn build_router(state: AppState) -> Router {
    Router::new()
        .route("/", get(handler))
        .with_state(state)
}

Here, the return type Router (that is, Router<()>) tells the compiler the function produces a router with nothing missing - ready to serve. The .with_state(state) call satisfies the AppState requirement, so the result is Router<()>, not Router<AppState>. This is useful when you split your application into modules.

Be careful with the annotation: writing -> Router<AppState> here would be misleading. It would tell the compiler the returned router is still missing an AppState, even though one was just provided - and a router that is still missing state cannot be served. If you want a function to return a router that still needs its state, leave .with_state(...) out of the function and let the caller provide it. Here are the two styles side by side so you can compare them directly.

Letting inference do the work needs no annotation at all. The compiler works out the finished type from the handler and the .with_state(...) call:

use axum::{Router, routing::get, extract::State};
#[derive(Clone)]
struct AppState { message: String }
async fn handler(State(state): State<AppState>) -> String {
    state.message
}
#[tokio::main]
async fn main() {
    let state = AppState { message: "Hello".to_string() };
    let app = Router::new()
        .route("/", get(handler))
        .with_state(state);
    // app is inferred as Router<()> - the state requirement is satisfied.
    // No annotation is needed here because passing `app` to
    // `axum::serve` below pins the finished type to `Router<()>`.
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The explicit annotation says the same thing in words. It is useful when the compiler cannot infer the type - for example when the function never serves the router - or when you want to document what the function returns:

use axum::{Router, routing::get, extract::State};
#[derive(Clone)]
struct AppState { message: String }
async fn handler(State(state): State<AppState>) -> String {
    state.message
}
#[tokio::main]
async fn main() {
    let state = AppState { message: "Hello".to_string() };
    let app: Router<()> = Router::new()
        .route("/", get(handler))
        .with_state(state);
    // The annotation pins the finished type to `Router<()>`, so this
    // compiles even though the router is never served here.
}

Both snippets produce the same result. The explicit annotation is helpful when the compiler cannot infer the type or when you want to document your code.

How the Type Parameter Appears in Real Projects

In a larger Axum application, you'll often split routes into separate modules. Each module might define handlers that use a shared AppState. When you combine these routes into a single router, you must ensure that the state type is consistent across all sub-routers.

For example, you might have a users module and a products module. Each defines handlers that need AppState. When you merge them, both routers must be Router<AppState>.

// In main.rs
use axum::{Router, routing::get};
use crate::state::AppState;
mod state;
mod users;
mod products;
#[tokio::main]
async fn main() {
    let state = AppState::new(); // Assume this creates the state
    // Build sub-routers; they will each be Router<AppState> because their handlers use State<AppState>.
    let users_router = users::router();
    let products_router = products::router();
    let app: Router<()> = Router::new()
        .merge(users_router)
        .merge(products_router)
        .with_state(state);
    // `app` is Router<()> - the state requirement is satisfied, so it can be served.
    // (The `Router<()>` annotation pins the finished type; the `users`,
    // `products`, and `state` modules here are sketched, not complete code.)
}

Here, users::router() and products::router() each return a Router<AppState> because their handlers use State<AppState> - that is, each sub-router is still missing its state. In Axum, you can build a router with routes that use State<T> without providing the state yet. The router's type parameter records the missing state, so it is Router<AppState> at that point. Then when you call .with_state(...) on the merged router, the requirement is satisfied and the final type becomes Router<()>. So you can build sub-routers without state, merge them (merging works because both are missing the same state type, AppState), and then attach state at the top level.

This pattern is common: build all routes without state, then add state at the very end. It keeps the router construction simple.

A Step-by-Step Guide to Converting a Stateless Router to a Stateful One

Sometimes you start with a stateless router and later need to add state. Here's a systematic approach.

1

Step 1: Identify the data your handlers need to share

Decide what information must be available across multiple handlers. It could be a database pool, a configuration struct, a cache, or anything else.

2

Step 2: Define a struct to hold that data

Create a struct with all the shared fields and derive Clone on it.

#[derive(Clone)]
struct AppState {
    // fields...
}
3

Step 3: Add `State<AppState>` to the handlers that need it

Modify your handler functions to accept a State extractor as one of their arguments. Example:

async fn handler(State(state): State<AppState>) -> impl IntoResponse {
    // use state
}
4

Step 4: Attach the state to the router with `.with_state(...)`

At the end of your router construction, call .with_state(state_value) where state_value is an instance of AppState.

5

Step 5: Compile and verify the router type is now `Router<()>`

If you see the type name via std::any::type_name_of_val, it will show axum::routing::Router - the () default is omitted, which means nothing is missing and the router can be served. If compilation fails, check that all handlers expecting state are covered and that the state type matches.

Following these steps will prevent most type-related errors.

When You Don't Need to Care About the Type Parameter

For very simple applications or examples, you might never think about Router<()> because you don't use state. That's perfectly fine. Axum's type parameter is mostly invisible until you start using State. The default Router<()> works out of the box, and you can add routes and serve your app without any type annotations.

But as soon as you need shared state, the type parameter becomes your friend. It ensures correctness and prevents a whole class of runtime errors.

You've Got This:

If you have successfully added a state type, compiled your router, and it shows axum::routing::Router (that is, Router<()>, nothing missing), you have correctly used the type parameter. The compiler has verified that all your state-consuming handlers are safe.

Summary

The Router type parameter in Axum is the key to type-safe shared state. A router starts as Router<()> when no handler needs state. When a handler uses State<AppState>, the router becomes Router<AppState> - still missing its state - and calling .with_state(...) with a value of type AppState satisfies that requirement, turning it back into Router<()>, the only form that can be served. This generic parameter allows the compiler to guarantee that handlers using State<T> are only used with a router that actually provides that state. By understanding this parameter, you can confidently build larger applications with shared data, avoid common pitfalls like forgetting to derive Clone or mismatching state types, and take full advantage of Axum's compile-time guarantees.

The decision to carry forward is simple. If a handler needs shared data, let the router's type show the missing state and satisfy it once with .with_state(...) at the end of the chain. If no handler needs shared data, leave state out entirely and keep the router as Router<()>. And whenever a router is built in a function that never serves it, write the finished type out - let app: Router<()> = ... - because the compiler cannot guess a finished type that nothing pins down.