Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 38 ยท Routers and Handlers

Nesting and Merging Axum Routers

Split an Axum app into modules with Router::nest, nest_service and merge: prefixes, stripped paths, OriginalUri, conflicts and the 0.8 root-nesting rule.

A real service has dozens of routes: users, posts, admin pages, health checks. Putting all of them in one function turns into a wall of .route(...) calls. Axum lets you build small routers, one per feature, and combine them. There are two tools: nest, which mounts a router under a path prefix, and merge, which pours the routes of one router into another.

This lesson shows both, what the inner handlers see, what happens on conflicts, and a runnable model of prefix stripping. The previous lesson on path parameters is useful background, because nesting works with captures too.

nest: mount a router under a prefix

Rust
use axum::{routing::get, Router};

fn users() -> Router {
    Router::new()
        .route("/", get(list_users).post(create_user))
        .route("/{id}", get(show_user))
}

fn posts() -> Router {
    Router::new().route("/", get(list_posts))
}

fn api() -> Router {
    Router::new()
        .nest("/users", users())
        .nest("/posts", posts())
}

async fn list_users() -> &'static str { "all users" }
async fn create_user() -> &'static str { "created" }
async fn show_user() -> &'static str { "one user" }
async fn list_posts() -> &'static str { "all posts" }

With this layout GET /users goes to list_users, POST /users to create_user, GET /users/7 to show_user and GET /posts to list_posts. The users() router does not know where it is mounted. That is the point: you can move the whole feature under /api/v1 by changing one line.

Nesting can go several levels deep:

Rust
fn app() -> Router {
    Router::new().nest("/api/v1", api())
}

Now show_user answers at /api/v1/users/7.

What the inner handler sees

Axum strips the prefix before the nested router matches. Inside users() the route is plain /{id}. That also changes what some extractors report:

  • Uri shows the stripped path (/7).
  • OriginalUri shows the full path the client used (/api/v1/users/7). Use it for logging and for building absolute links.
  • MatchedPath shows the full route pattern, which is handy as a metrics label.

Captures in the prefix itself work as you would hope:

Rust
Router::new().nest("/orgs/{org}", org_routes())
// inside org_routes, Path<(String, u32)> sees {org} first

Rules in Axum 0.8

  • Nesting at the root, nest("/", router), panics. Use merge for that, and fallback for catch-all behaviour.
  • A nested router's own fallback handles misses inside its prefix; the outer fallback handles everything else. Fallbacks are the next lesson.
  • Axum 0.8 no longer redirects between /users and /users/. They are different paths. Pick one style and stay with it.

nest_service: mount any Tower service

nest_service mounts a Tower Service instead of a Router. Typical use: static files with tower-http.

Rust
use tower_http::services::ServeDir;

let app = Router::new()
    .route("/", get(home))
    .nest_service("/assets", ServeDir::new("public"));

A request for /assets/logo.svg is handed to ServeDir with /logo.svg as its path. The Tower lesson explains why a file server and a router can be used interchangeably: both are services.

merge: combine routers at the same level

merge copies routes from another router without adding a prefix:

Rust
fn app() -> Router {
    Router::new()
        .merge(public_routes())
        .merge(admin_routes())
}

Merge is the better tool when each module already knows its full paths, or when you want a layer on a group of routes only:

Rust
fn app(state: AppState) -> Router {
    let public = Router::new().route("/login", post(login));
    let private = Router::new()
        .route("/me", get(me))
        .route("/settings", get(settings))
        .layer(from_fn_with_state(state.clone(), require_login));

    public.merge(private).with_state(state)
}

The login layer wraps /me and /settings but not /login. The middleware lesson uses exactly this shape.

Conflicts. If two merged routers register the same path and the same method, Axum panics while building the router. That is deliberate: you find the mistake when the program starts, not when a customer hits the wrong handler. The same path with different methods merges fine.

Which should I use?

Situation Use
A feature module with its own prefix (/users/...) nest
Mounting a file server or another Tower service nest_service
Splitting by concern, paths already complete merge
Applying a layer to part of the app build a sub-router, .layer(...), then merge or nest

A runnable model of nesting and merging

This stand-in keeps a route table. nest prefixes every path in the inner table and merge joins two tables and rejects duplicates, like Axum does at start-up. It is a model, not Axum itself.

Rust Stand-in: nest and merge on a route table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

DELETE /api/v1/users/7 gets a 405 because the path exists for another method, and /users is a 404 because nothing is mounted without the prefix. The deliberate clash prints a panic message (overlapping route: GET /health); the line you care about is the final true.

Organising a bigger app

A layout that scales well:

TEXT
src/
  main.rs          // builds the app: merge + layers + state
  routes/
    mod.rs         // pub fn router() -> Router<AppState>
    users.rs       // pub fn router() -> Router<AppState>
    posts.rs

Each module exposes pub fn router() -> Router<AppState>, and routes/mod.rs nests them. The <AppState> type parameter means "still needs state"; with_state supplies it once at the top. See shared state.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A router is nested with nest("/api", inner). A client calls GET /api/items. What path does inner match against?

    Axum strips the prefix before the nested router matches. OriginalUri still holds the full path.
  2. 2. Which call is not allowed in Axum 0.8?

    Nesting at the root panics. Use merge to add routes without a prefix.
  3. 3. Two merged routers both define GET /health. What happens?

    Overlapping method and path combinations are detected at start-up, so the bug cannot reach production.
  4. 4. How do you protect only some routes with an authentication layer?

    A layer applies to the router it is called on, so group the protected routes into their own router first.

Summary

  • nest(prefix, router) mounts a router under a prefix and strips it from the path the inner router sees; OriginalUri keeps the full path.
  • nest_service mounts any Tower service, such as a static-file server.
  • merge combines routers without a prefix; duplicate method + path pairs panic at start-up.
  • Group routes into sub-routers to apply layers to some routes only.
  • Nesting at "/" is not allowed in 0.8: use merge.

Next: Fallbacks and Method Not Allowed