axum Router Overview and Usage

Understand the axum Router type - its purpose, creation, state handling, nesting, merging, and fallback behavior in an Axum web application

When you build a web server in Axum, the Router is the object that holds your entire application's routing table. It decides which piece of code should run for each incoming HTTP request. Think of it as the front desk of a hotel: a guest gives a room number, and the front desk knows exactly which hallway and door to send them to. Without a front desk, guests would wander aimlessly. Similarly, without a Router, your server would have no idea what code to execute when a request arrives.

This page explains the Router type itself, how to create one, how it manages state, and how you can combine multiple routers into a larger application. We will use simple code examples that compile and run, but we will not dive deeply into the specific methods for adding routes or the internals of handler functions - those are separate topics of their own. Here we focus on the Router as a container and coordinator.

Creating a Router

You always start building an Axum application by creating a new Router. The simplest possible router is created with Router::new(). This returns a Router that does not yet have any routes, so it will respond to every request with 404 Not Found.

Let's see the most basic example of a Router in context. This is a complete Rust file that you could place in src/main.rs of a new Axum project. We will explain the parts that involve the Router, but the other pieces (like tokio::main, axum::serve, TcpListener) are part of the overall server setup and are not the focus here.

use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(|| async { "Hello, world!" }));
    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();
}

The important line for us is Router::new(). This creates an empty router. We then immediately call .route("/", get(|| async { "Hello, world!" })) to add a single route for the root path. The get(...) part is from axum::routing::get and is a method router that only responds to HTTP GET requests. The closure || async { "Hello, world!" } is a handler - it's the code that runs when that route is hit. For now, treat the handler as a black box that returns a string.

After we build the router, we pass it to axum::serve. That function requires a Router<()> - that is, a router that is fully configured and does not require any additional state to be supplied. We will talk about that type parameter soon.

If you run this program and open http://127.0.0.1:3000/ in a browser, you'll see Hello, world!. If you go to any other path, like /foo, you'll get a 404 Not Found response with an empty body. That is the router's default behavior when no route matches.

Router is ready:

A Router returned by Router::new() is immediately usable once you have added at least one route. The router itself does not start the server; it is just a blueprint that the server uses to decide how to handle requests.

The State Type Parameter

You may have noticed that the type of app in the example above is not written out. Axum's Router type has a generic parameter S that represents "missing state". The full type is Router<S>. When you create a router with Router::new(), you get Router<()>, because there is no missing state - the router is complete. But routers can also be created in an "incomplete" form that requires you to provide some application state before they can be used. We'll explore this now.

What is application state?

In many web applications, your handlers need access to shared resources: a database connection pool, a configuration object, or a cache. Instead of hardcoding these resources inside each handler, you store them once in an application state object and pass that state to every handler that needs it. Axum's Router supports this pattern through the State extractor. But before we can use state in handlers, we need to attach it to the router.

Here is a basic example of a router that expects a state of type AppState. We first create a struct to hold our state, then we create a router that knows it will eventually receive that state. The router is built with .with_state(...) to provide the actual state value. The result is a Router<()> that can be served.

use axum::{
    extract::State,
    routing::get,
    Router,
};
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
    app_name: String,
}
async fn handler(State(state): State<Arc<AppState>>) -> String {
    format!("Welcome to {}", state.app_name)
}
#[tokio::main]
async fn main() {
    let shared_state = Arc::new(AppState {
        app_name: String::from("My Axum App"),
    });
    let app = Router::new()
        .route("/", get(handler))
        .with_state(shared_state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Let's break down what's happening. We define AppState and derive Clone. We wrap it in an Arc (atomic reference counting) so that multiple handler calls can safely share the same data without copying it. The handler function takes a State<Arc<AppState>> extractor as its argument. When the handler runs, Axum automatically provides the state that was attached to the router.

The router is built with Router::new(), then .route(...), then .with_state(shared_state). Notice the order: we first add routes that may eventually use state, then we call with_state to provide the actual state object. After calling with_state, the router's type changes from Router<Arc<AppState>> (missing state - the type is Arc<AppState> because that is exactly what the handler's State<Arc<AppState>> extractor asks for) to Router<()> (complete). That is why we can pass app to axum::serve.

Why Arc?:

The state is cloned for every request. If you wrap your state in an Arc, the clone is cheap because it just increments a reference counter rather than duplicating the entire data. If your state struct is small and contains only fields that are cheap to clone (like integers or strings), you could derive Clone directly and skip the Arc. In practice, many people use Arc for clarity and future-proofing.

If you forget to call .with_state on a router that expects state, the compiler will stop you. The router type will still be Router<Arc<AppState>>, and axum::serve only accepts Router<()>. This is a deliberate design: Axum uses the type system to make it impossible to run a router that has not been given the state it needs. This prevents a whole category of runtime errors.

Missing with_state causes a compile error:

If you remove the .with_state(shared_state) line from the example above, the code will not compile. The error says that Router<Arc<AppState>> does not implement the Service trait that axum::serve requires - only a complete Router<()> does. This is Axum protecting you from forgetting to provide required state. Always check that your router is fully configured before passing it to serve.

Providing substate

Sometimes a handler only needs part of the application state, not the whole AppState. For example, your state might contain both a database pool and an API client, but a particular handler only uses the API client. You can still attach the full state, but in your handler you can extract a substate using the FromRef trait. The details of FromRef are beyond this page, but the important concept is that the router itself only knows about the full state; how handlers pick and choose from that state is a separate concern. The Router remains unchanged - you always call with_state with the entire state object.

Nesting Routers

As your application grows, keeping all routes in one huge Router becomes unmanageable. Axum lets you split routes into smaller routers and then combine them. The two main methods for this are nest and merge. They are similar but have an important difference.

  • nest mounts a child router under a path prefix. For example, nest("/api", api_router) makes all routes inside api_router available under /api/....
  • merge combines two routers by combining their route tables directly. The paths defined in the merged router are used as-is, without a prefix.

Here is an example of nest:

use axum::{routing::get, Router};
async fn list_users() -> &'static str {
    "List of users"
}
async fn create_user() -> &'static str {
    "User created"
}
async fn get_user() -> &'static str {
    "Single user"
}
#[tokio::main]
async fn main() {
    let user_routes = Router::new()
        .route("/", get(list_users).post(create_user))
        .route("/{id}", get(get_user));
    let app = Router::new()
        .nest("/api/users", user_routes);
    // Now the routes are:
    // GET /api/users          -> list_users
    // POST /api/users         -> create_user
    // GET /api/users/{id}     -> get_user
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The child router user_routes defines routes relative to its own root. When you nest it under /api/users, Axum prepends that prefix to all inner routes. Notice that the inner route "/" becomes /api/users (the trailing slash is important; we'll discuss this shortly).

Now an example of merge:

use axum::{routing::get, Router};
async fn home() -> &'static str {
    "Home page"
}
async fn health() -> &'static str {
    "OK"
}
#[tokio::main]
async fn main() {
    let home_router = Router::new().route("/", get(home));
    let health_router = Router::new().route("/health", get(health));
    let app = Router::new()
        .merge(home_router)
        .merge(health_router);
    // Routes: GET /          -> home
    //         GET /health    -> health
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

With merge, both routers' routes are combined into one routing table. There is no path prefix added. This is useful when different parts of your application are defined independently and you want to combine them all at the top level.

Nesting and trailing slashes:

When you nest a router, the prefix handling is strict about slashes. If you nest("/api", inner) and inner has a route "/", the resulting path is /api. If inner has a route "/users", the result is /api/users. If you used nest("/api/", inner) (with trailing slash), then inner's "/" becomes /api/ and inner's "/users" becomes /api/users. In practice, most people use nest("/api", ...) without the trailing slash and then define inner routes with no leading slash confusion. The key is to test your endpoints after nesting to be sure they match what you expect.

Nesting and merging are both ways to compose a larger Router. They do not change the fundamental nature of the Router - it is still one routing table that the server uses to match requests.

Fallbacks and 404 Handling

When a request arrives and no route matches, Axum's default behavior is to return a 404 Not Found response with an empty body. This is often fine for APIs, but you may want to customize what happens when a route is not found. You can do this with the fallback method on Router.

use axum::{routing::get, http::StatusCode, Router};
async fn not_found() -> (StatusCode, &'static str) {
    (StatusCode::NOT_FOUND, "Sorry, that page does not exist.")
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(|| async { "Home" }))
        .fallback(not_found);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Now if someone requests /unknown, they'll get a 404 status code and the message "Sorry, that page does not exist." The fallback method accepts any handler and will be called for any request that does not match a route.

Fallbacks also work with nested routers. If a nested router does not define its own fallback, it inherits the fallback from the outer router. This can be useful to have a consistent 404 page across your whole application.

Fallback can mask missing routes:

If you set a fallback that returns a successful status code (like 200), then requests to unknown paths will appear successful. Make sure your fallback actually returns a 404 or another appropriate error status to avoid hiding routing mistakes.

Common Mistakes and Pitfalls

Overlapping routes cause a panic

Axum is strict about route definitions. If you try to register the exact same path twice for the same method, the Router will panic (crash) when you call the builder method. For example:

use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(|| async { "First" }))
        .route("/", get(|| async { "Second" })); // This will panic!
}

The second .route("/", ...) will trigger a panic because / is already mapped. This is a safety feature: it prevents accidentally overriding a route. If you need to change a route, you must remove the old one or use a different path. The panic message will tell you exactly which path is duplicated.

Route overlap panics at runtime:

Route registration happens when you build the router, not when a request arrives. That means if you have a route overlap, your program will crash immediately during startup, not after the server is running. This is usually what you want, but it can be surprising if you are not expecting it.

Forgetting to provide required state

As we saw earlier, if you build a router with routes that use the State extractor but you do not call .with_state, the compiler will refuse to compile. However, there is a subtle case: if you have a router that itself does not require state, but you nest a router that does require state, you must make sure the state is provided before nesting or at some point. Axum's type system will catch missing state, but the error messages can be complex. The rule of thumb: always call with_state at the point where the state becomes available, and do it before you try to serve the router.

Leading slashes in nested routes

Every route path must start with / - including routes inside a nested router. Router::route panics if the path does not start with a slash, so "users" without a leading slash is never valid; always write "/users". The same rule applies to the prefix you pass to nest: nest("/api", inner) is correct, while nest("api", inner) will panic. In short, always start route paths with /, at the top level and inside nested routers alike.

Summary

The Router is the central piece of any Axum application. It is a declarative mapping from HTTP paths and methods to handler functions. You start with Router::new(), add routes, optionally attach state with with_state, combine sub-routers with nest or merge, and set a fallback for unmatched requests. The type system ensures that a router is complete before it can be served, preventing many common mistakes.

As you continue building your Axum project, you will use the Router constantly. The next logical step after understanding the router is to learn how to define routes using the route method and the different HTTP verb helpers like get, post, and so on. But for now, remember this: the router is just a container that holds your application's map from requests to code. The more you understand how to compose and configure it, the easier it will be to structure larger applications cleanly.