Axum Router Merge Method

Learn how to combine multiple Axum routers using the merge method, including modular route organization, overlapping routes, fallbacks, state types, common mistakes, and practical examples.

When you build a web application with Axum, you will quickly find that putting every single route into one giant Router becomes hard to manage. The merge method exists to solve exactly that problem: it lets you take two separate Router values and combine them into one, so each part of your application can own the routes it cares about.

A First Look at Merging Two Routers

Start with the smallest possible example. Create two routers, give each one a route, and then merge them together into a single application router.

// main.rs
use axum::{Router, routing::get};
#[tokio::main]
async fn main() {
    // First router: owns the /hello route
    let hello_router = Router::new()
        .route("/hello", get(|| async { "Hello from the first router!" }));
    // Second router: owns the /world route
    let world_router = Router::new()
        .route("/world", get(|| async { "Hello from the second router!" }));
    // Merge them into one router
    let app = hello_router.merge(world_router);
    // 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 with cargo run, then open your browser and visit http://127.0.0.1:3000/hello and http://127.0.0.1:3000/world. You will see the two different messages. That is the entire idea: two routers, each with their own route, became one router that knows both routes.

The merge method consumes the router you call it on and the router you pass in, returning a new Router that contains the routes from both. It does not modify either original router; it creates a combined one. This is why we write let app = hello_router.merge(world_router); and then use app, not hello_router.

Setup Confirmed:

If you see both messages when you visit the two paths, you have successfully merged two routers. The combined router is now serving routes from both.

What Does merge Actually Do?

Mechanically, merge takes all the routes from the router you pass in and adds them to the router you call it on. The result is a single Router with no memory of where each route originally came from. Think of it like pouring two boxes of labeled folders into one larger box: every folder is now in one place, and you can open any of them by looking at the label (the path).

The order in which routes are registered does not matter to matching. When a request comes in, Axum matches it by path and method against the combined route table - a static segment beats a parameter, and a parameter beats a wildcard, regardless of which router contributed the route or which merge call added it. The merged router keeps no memory of which side a route came from.

That has one sharp consequence. If two routers define the same path with the same method, there is no "first one wins" rule and no shadowing: the second registration panics. The next section shows that case directly.

Overlapping Routes Panic on Merge

Imagine two routers both define a route for /status. The first router returns one message, the second returns a different message. After merging, which one runs? Neither - the program never gets that far.

// main.rs
use axum::{Router, routing::get};
#[tokio::main]
async fn main() {
    let first = Router::new()
        .route("/status", get(|| async { "Status from first router" }));
    let second = Router::new()
        .route("/status", get(|| async { "Status from second router" }));
    // This merge panics: Axum cannot hold two handlers for GET /status.
    let app = first.merge(second);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Running this program prints a panic and the server never starts:

thread 'main' panicked at ...:
Overlapping method route. Handler for `GET /status` already exists

There is no precedence to tune here. Reversing the merge to second.merge(first) panics exactly the same way, because the overlap is in the route table itself, not in the order the routers were combined. The only fix is to define the route in one router, or to give the two routes different paths or methods.

Overlapping Routes Panic:

If you merge two routers that both define the same path and method, the merge call panics at registration and the application never starts. This is often a source of confusion for beginners who expect the first or second route to quietly win. There is no shadowing and no priority - keep each path and method defined in exactly one router.

Chaining Multiple merge Calls

One router can absorb as many other routers as you need. Because merge returns a new Router, you can chain calls one after another.

// main.rs
use axum::{Router, routing::get};
#[tokio::main]
async fn main() {
    let users = Router::new()
        .route("/users", get(|| async { "User list" }));
    let posts = Router::new()
        .route("/posts", get(|| async { "Post list" }));
    let comments = Router::new()
        .route("/comments", get(|| async { "Comment list" }));
    // Merge all three into one router
    let app = users
        .merge(posts)
        .merge(comments);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Each merge adds the routes from the argument router to the combined router. The chaining order is only a matter of reading: it says which routers are combined, not which routes win. If any two of them defined the same path and method, the merge would panic at registration, whichever order you chained them in.

You could also write it as separate statements if that reads better:

let mut app = users;
app = app.merge(posts);
app = app.merge(comments);

But chaining is more common in small examples.

Merging Routers from Different Files

A very common real-world pattern is to define each feature of your application in its own module, each exporting its own Router. Then in a central place (often main.rs or a routes/mod.rs file), you merge all those feature routers together. This keeps every feature isolated and makes the top-level application router simple.

Suppose you have three files: users.rs, posts.rs, and main.rs.

First, users.rs:

// users.rs
use axum::{Router, routing::get};
pub fn router() -> Router {
    Router::new()
        .route("/users", get(|| async { "List of users" }))
        .route("/users/{id}", get(|axum::extract::Path(id): axum::extract::Path<u32>| async move {
            format!("User {id}")
        }))
}

Then posts.rs:

// posts.rs
use axum::{Router, routing::get};
pub fn router() -> Router {
    Router::new()
        .route("/posts", get(|| async { "List of posts" }))
}

Finally, main.rs merges both:

// main.rs
mod users;
mod posts;
use axum::Router;
#[tokio::main]
async fn main() {
    let app = Router::new()
        .merge(users::router())
        .merge(posts::router());
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Notice that we start with Router::new() and then merge the feature routers into it. The empty router contributes no routes. Merging simply combines the route tables - there is no "checking order": overlapping routes with the same path and method panic at registration, regardless of merge order.

State Type Must Match:

All routers merged together must use the same state type. If your application uses a shared state (for example a database connection pool), every router must be the same type - either all Router<AppState> with the state supplied once on the merged router, or all Router<()> after each router got its own state with with_state. You cannot merge a Router<AppState> with a Router<()>. The usual fix is to call .with_state(state) on the router that still needs state, which supplies it and lets that router merge with the others.

merge vs. nest - One Sentence of Contrast

Because these two methods are often confused, here is the shortest possible explanation: merge combines routers at the same path level, while nest mounts one router under a path prefix. merge gives you two routes /a and /b; nest gives you /prefix/a and /prefix/b. This page focuses only on merge; the nest method is covered elsewhere.

A Practical Example - Merging an API Router with a Web Router

Let's build a slightly larger example where you have an API router that returns JSON and a frontend router that returns HTML. You keep them separate, then merge them into the main application.

First, define a helper to create a JSON response. We'll use Axum's Json extractor. This example also uses the json! macro from the serde_json crate, so add it to your dependencies:

Cargo.toml
[dependencies]
axum = "0.8.9"
tokio = { version = "1", features = ["full"] }
serde_json = "1"
// main.rs
use axum::{
    Router,
    routing::get,
    Json,
};
use serde_json::json;
// API router: returns JSON
fn api_router() -> Router {
    Router::new()
        .route("/api/health", get(|| async {
            Json(json!({ "status": "ok" }))
        }))
        .route("/api/users", get(|| async {
            Json(json!([{ "id": 1, "name": "Alice" }]))
        }))
}
// Web router: returns plain text or HTML
fn web_router() -> Router {
    Router::new()
        .route("/", get(|| async { "Welcome to the homepage" }))
        .route("/about", get(|| async { "About us page" }))
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .merge(api_router())
        .merge(web_router());
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Now http://127.0.0.1:3000/api/health returns {"status":"ok"}, http://127.0.0.1:3000/api/users returns a JSON array, and http://127.0.0.1:3000/ returns plain text. All routes coexist peacefully because they have different paths.

This separation is especially useful when your API and your web frontend have different middleware or error handling needs. By building separate routers, you can attach different middleware to each before merging them, keeping concerns isolated.

Common Mistakes and Misconceptions

Mistake 1: Thinking merge Modifies the Original Routers

merge consumes the receivers. After you write:

let app = router_a.merge(router_b);

you can no longer use router_a or router_b in the same scope. Rust's ownership rules will cause a compile error if you try. This is not a bug; it's the method's design to avoid accidental reuse of a partially merged router.

If you need to keep the original routers alive, you can clone them (if they implement Clone, which Router does) or restructure your code to not need them after merging.

Mistake 2: Thinking Merge Order Gives Precedence

There is no precedence in merge. If you merge users.merge(posts) and both define /dashboard with the same method, registering the second one panics with Overlapping method route. Handler for \GET /dashboard` already exists`. The fix is not to reorder the merge calls - it is to define the route in only one router, or to give the two routes different paths or methods.

Mistake 3: Merging Routers with Different State Types

If you have a router that uses Router<AppState> and another that uses Router<()>, you cannot merge them. The compiler error will say something like "expected Router<AppState>, found Router<()>". You must make both use the same state type. The usual fix is to provide the state to the router that needs it: calling .with_state(state) on the Router<AppState> router turns it into a Router<()> (its handlers' state is now supplied), so it can merge with the stateless router. Alternatively, give both routers the same missing state type and provide the state once on the merged router.

State only reaches routes added before with_state:

Calling .with_state(state) supplies state to the routes already on that router. A stateful route added afterwards does not get that state - add the route first and then call with_state, or provide the state again after adding the route.

Mistake 4: Confusing merge with nest

A beginner might write:

let app = users.merge(posts);

thinking this will make posts available under /users/posts. It will not. merge adds posts' routes at the root level, so /posts is still /posts. If you need a prefix, use nest instead.

Compiler Error on Mismatched State:

Trying to merge two routers with different state generic parameters is a compile-time error, not a runtime one. The compiler will point at the merge call with a type mismatch. This is actually good: it prevents a class of bugs where handlers expect state that isn't there.

Merging Fallback Routes

A router can have a fallback - a route that matches any path that no other route matches. When you merge routers, only one of them may have a custom fallback: if both routers have one, merge panics with Cannot merge two \Router`s that both have a fallback`. If exactly one has a custom fallback, the merged router keeps it, whichever side it came from.

// main.rs
use axum::{Router, routing::get, http::StatusCode};
#[tokio::main]
async fn main() {
    // Specific routes
    let api = Router::new()
        .route("/api/health", get(|| async { "OK" }));
    // Fallback for everything else
    let fallback = Router::new()
        .fallback(|| async { (StatusCode::NOT_FOUND, "Nothing here") });
    // Merge the two routers
    let app = api.merge(fallback);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Now visiting /api/health gives OK, and visiting any other path like /random gives 404 Nothing here. The fallback from the fallback router is kept by the merged router, so it only runs if nothing else matched. This is a clean way to add a global 404 handler without nesting. (If the api router also had its own fallback, this merge would panic - only one custom fallback is allowed per merged router.)

Using merge Inside Functions That Return Routers

A common pattern is to have a function that builds a complete router by merging several sub-routers. For example:

fn build_app() -> Router {
    let admin = Router::new()
        .route("/admin", get(|| async { "Admin panel" }));
    let public = Router::new()
        .route("/public", get(|| async { "Public page" }));
    let api = Router::new()
        .route("/api", get(|| async { "API root" }));
    Router::new()
        .merge(public)
        .merge(admin)
        .merge(api)
}

Then in main, you call let app = build_app();. This keeps your startup code tidy and makes it easy to test the router in isolation using tower::ServiceExt::oneshot (though testing is a separate topic).

How merge Relates to Router Type Parameters

Router is generic over the state type S. When you call merge, the returned router has the same state type S as both input routers. If both input routers are Router<()>, the result is Router<()>. If both are Router<MyState>, the result is Router<MyState>. There is no automatic conversion; you must have the same type.

Because merge takes self by value and returns a new Router, it is a consuming builder method. This is why you can chain it and why you cannot use the original router after merging.

Summary

The merge method is the tool you use to combine two Axum routers into one, keeping their routes at the same path level. Merge order gives no priority: if two routers define the same path and method, registration panics with an overlapping-route error, whichever order you merge them in. Merge is ideal for splitting your application into feature modules, each exporting its own Router, and then assembling them in a central place.

The most important things to remember are that overlapping routes panic (there is no shadowing), that only one merged router may carry a custom fallback, and that every router you merge has the same state type. Once you understand those points, merge becomes a straightforward and powerful way to keep large Axum applications organized.

If you find yourself needing to mount routers under a common prefix, that's the job of the nest method, which is covered separately. For combining routers at the same level, merge is exactly what you need.