Understanding Axum's nest Method for Modular Routing

Learn how to use Axum's nest method to organize routes into nested routers with path prefixes, enabling modular and maintainable web applications.

Axum's nest method lets you mount an entire Router under a specific URL path prefix. It is the primary tool for keeping large route tables organized by grouping related endpoints together, and it is especially useful when building APIs with versioned or feature-based sections. This page explains what nest does, how it works, and how to use it correctly with many examples.

Why the nest Method Exists

When an Axum application grows beyond a handful of endpoints, listing every route directly on the main Router becomes hard to read and maintain. You end up with a long chain of .route() calls, often repeating similar path prefixes like /api/users, /api/posts, /api/comments. The nest method solves this by letting you create smaller, focused routers and then attach them to a parent router under a common prefix.

A mental model that helps beginners: imagine a file system. The main Router is the root directory, and each nested router is a subdirectory. Just as files inside a subdirectory are accessed by their full path from the root, routes inside a nested router are accessed by the prefix plus the route's own path.

What nest does not do:

The nest method does not copy or duplicate routes; it merges the child router's routes into the parent with the given prefix added. The child router is consumed by nest (moved into the parent), so it cannot be reused afterwards - to mount the same routes twice, build them with a function that returns a fresh router on each call. The routes themselves are registered once on the final application router.

A Minimal nest Example

The smallest possible use of nest involves two routers: a child router with one route, and a parent router that mounts the child under a prefix.

use axum::{Router, routing::get};
async fn hello() -> &'static str {
    "Hello from nested router!"
}
#[tokio::main]
async fn main() {
    // Child router with a single route at /hello
    let api_router = Router::new()
        .route("/hello", get(hello));
    // Parent router mounts the child under /api
    let app = Router::new()
        .nest("/api", api_router);
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

When you run this and visit http://localhost:3000/api/hello, you will see the message Hello from nested router!. If you try http://localhost:3000/hello or http://localhost:3000/api, you will get a 404 Not Found because those paths do not match any route after the prefix is applied.

Here is what happens mechanically: the parent router receives the incoming request path /api/hello. It sees that the first path segment is /api, which is the prefix given to nest. The parent strips off that prefix, leaving /hello. It then asks the child router to handle /hello. The child router finds its /hello route and runs the handler.

A common beginner mistake is to include a trailing slash in the prefix or the child route without thinking about how slashes are joined. Axum handles slashes predictably: the prefix and child route are concatenated with a single slash separator.

Trailing slash can cause a 404:

If you write nest("/api/", api_router) and the child route is /hello, the resulting path is /api/hello. That works. But if you also have a route /hello/ (with trailing slash) in the child, a request to /api/hello/ will match, while a request to /api/hello will not. Be consistent with your use of trailing slashes in both prefix and child paths to avoid surprises.

How Path Prefixes Are Applied

The nest method takes two arguments: a path string and a child Router. The path string is the prefix. It can be a simple static prefix like "/api" or "/admin", or it can contain route parameters, which we will see later.

The child router's routes are always defined relative to the root of that child router. So a route defined as /users inside a child router mounted at /api becomes /api/users in the final application. Nested routers are completely independent; they do not know about the parent prefix.

This separation is powerful because you can build the child routes with a function that returns a fresh router on each call, and mount the result under different prefixes. For example, the same user_routes() function could be mounted at /v1 and /v2 for API versioning, and any changes inside the child router are automatically reflected in both places. You cannot reuse one router value twice, because nest consumes the child - the function is what makes the reuse possible.

Let's see a more complete example with several routes inside the child router and two different prefixes.

use axum::{Router, routing::get};
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"
}
fn user_routes() -> Router {
    Router::new()
        .route("/", get(list_users))
        .route("/create", get(create_user))
        .route("/{id}", get(get_user))
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .nest("/v1", user_routes())
        .nest("/v2", user_routes());
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Now the following URLs all work:

  • GET /v1 → "List of users"
  • GET /v2 → "List of users"
  • GET /v1/create → "User created"
  • GET /v2/create → "User created"
  • GET /v1/42 → "Single user"
  • GET /v2/99 → "Single user"

Notice that the child router has a route at / which matches the prefix exactly. In Axum, a route path of / inside a nested router will match the prefix with no additional segment. This is a common pattern for index endpoints of a resource group.

Empty path in child router:

A route path of / is not the same as an empty string. An empty string "" would be invalid; always use / when you want to match the exact prefix with no extra path.

Nesting with Path Parameters in the Prefix

The prefix passed to nest is not limited to static text. It can include path parameters using the same brace syntax as ordinary routes. This allows you to scope an entire sub-router under a dynamic segment.

For example, imagine a blog application where each user has their own set of posts. Instead of defining routes like /users/{user_id}/posts, you can nest a post router under /users/{user_id}.

use axum::{Router, routing::get, extract::Path};
async fn list_posts(Path(user_id): Path<String>) -> String {
    format!("Listing posts for user {}", user_id)
}
async fn create_post(Path(user_id): Path<String>) -> String {
    format!("Creating a post for user {}", user_id)
}
fn post_routes() -> Router {
    Router::new()
        .route("/", get(list_posts))
        .route("/new", get(create_post))
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .nest("/users/{user_id}/posts", post_routes());
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

With this setup, a request to GET /users/alice/posts will call list_posts with user_id equal to "alice". A request to GET /users/bob/posts/new will call create_post with user_id equal to "bob".

How does this work? The parent router parses the path and captures the parameter user_id from the prefix. Then it strips the full prefix /users/alice/posts from the incoming path, leaving / or /new. That remaining path is passed to the child router. The child router's handler for / or /new can still extract the path parameter from the parent prefix using Path<String> because Axum makes captured parameters available to all handlers in the request path, not just the handler that defined the route pattern.

This is a very useful pattern because the child router's handlers can access any parameters that appear in any part of the full path, including those in the nest prefix.

Path parameters are shared across nesting boundaries:

Handlers inside a nested router can extract path parameters that were defined in the parent's nest prefix. In the example above, list_posts and create_post both receive the user_id from the /users/{user_id}/posts prefix even though they are defined in the child router.

A subtle point: the child router does not need to declare the parameter in its own route patterns because the parameter is already part of the parent's pattern. The child router only sees the remaining path after the prefix is removed. If you tried to define a route inside the child router as /{user_id}/posts, you would actually be matching a path like /users/alice/posts/alice/posts, which is likely not what you want.

Multiple Levels of Nesting

You can nest routers inside nested routers. This creates a tree of routes and is extremely helpful for organizing deeply structured APIs.

Consider an API for an e-commerce platform with sections for admin and public store. You might have a top-level admin_router nested under /admin, and inside that, a products_router nested under /products, and further perhaps a reviews_router under /products/{product_id}/reviews.

use axum::{Router, routing::get, extract::Path};
async fn admin_dashboard() -> &'static str {
    "Admin dashboard"
}
async fn list_products() -> &'static str {
    "All products"
}
async fn list_reviews(Path(product_id): Path<String>) -> String {
    format!("Reviews for product {}", product_id)
}
fn reviews_router() -> Router {
    Router::new()
        .route("/", get(list_reviews))
}
fn products_router() -> Router {
    Router::new()
        .route("/", get(list_products))
        .nest("/{product_id}/reviews", reviews_router())
}
fn admin_router() -> Router {
    Router::new()
        .route("/", get(admin_dashboard))
        .nest("/products", products_router())
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .nest("/admin", admin_router());
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

This creates the following routes:

  • GET /admin → admin dashboard
  • GET /admin/products → list all products
  • GET /admin/products/123/reviews → reviews for product 123

Each nested router only knows about its own immediate prefix. The reviews_router sees paths like / after the parent routers have removed /admin/products/123/reviews. Yet the handler can still extract product_id because that parameter is defined in the middle-level products_router's nest prefix.

The same rule applies at any depth: parameters defined in any ancestor's nest prefix are available to all descendant handlers.

Do not repeat the full path in nested routes:

When you have multiple levels of nesting, always define routes in a child router relative to that child's own root. For example, inside products_router, do not write .route("/products/{product_id}/reviews", ...) because the parent has already applied /admin/products. If you do, the full path becomes /admin/products/products/{product_id}/reviews, which almost certainly is wrong and will lead to confusing 404 errors.

Sharing State Across Nested Routers

Nested routers often need access to application state, such as a database connection pool or configuration. In Axum, state is shared through the router's type parameter, and nested routers can either have their own state or use the parent's state.

The simplest approach is to make the child router use the same state type as the parent. You do this by ensuring both routers have the same generic parameter S. When you call nest, Axum checks that the state types are compatible.

Here is an example where both parent and child use Arc<AppState> as their state.

use axum::{Router, routing::get, extract::State};
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
    app_name: String,
}
async fn home(State(state): State<Arc<AppState>>) -> String {
    format!("Welcome to {}", state.app_name)
}
async fn api_info(State(state): State<Arc<AppState>>) -> String {
    format!("API for {}", state.app_name)
}
fn api_router() -> Router<Arc<AppState>> {
    Router::new()
        .route("/info", get(api_info))
}
#[tokio::main]
async fn main() {
    let state = Arc::new(AppState {
        app_name: "My App".to_string(),
    });
    let app = Router::new()
        .route("/", get(home))
        .nest("/api", api_router())
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Because api_router is declared as Router<Arc<AppState>>, the parent can nest it, and both share the same state instance. If the child router had a different state type, the nest method would produce a compile error asking you to provide the appropriate state.

A less common but valid approach is to give the child router its own state. In that case, you need to call .with_state() on the child router before nesting it, and the parent's state type can be different. This is useful when a submodule has completely independent state requirements.

use axum::{Router, routing::get, extract::State};
use std::sync::Arc;
#[derive(Clone)]
struct ParentState {
    app_name: String,
}
#[derive(Clone)]
struct AdminState {
    admin_email: String,
}
async fn home(State(state): State<Arc<ParentState>>) -> String {
    format!("Welcome to {}", state.app_name)
}
async fn admin_dashboard(State(state): State<Arc<AdminState>>) -> String {
    format!("Admin contact: {}", state.admin_email)
}
fn parent_routes() -> Router<Arc<ParentState>> {
    Router::new().route("/", get(home))
}
#[tokio::main]
async fn main() {
    let parent_state = Arc::new(ParentState {
        app_name: "My App".to_string(),
    });
    let admin_state = Arc::new(AdminState {
        admin_email: "admin@example.com".to_string(),
    });
    let admin_router = Router::new()
        .route("/", get(admin_dashboard))
        .with_state(admin_state);
    let app = Router::new()
        .nest("/admin", admin_router)
        .merge(parent_routes().with_state(parent_state));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Here, admin_router has state type Arc<AdminState>, while the parent has Arc<ParentState>. Because admin_router already has its state set (via .with_state()), it is a Router<()> from the parent's perspective. That only works when the parent is a Router<()> too at the moment of nesting, so the parent's own stateful routes live in a separate router that is given its state and merged in afterwards.

Why the extra step? nest requires both sides to have the same state type. The parent cannot be Router<Arc<ParentState>> while nesting a Router<()> child - that combination does not compile. So the parent's stateful routes are built as their own Router<Arc<ParentState>>, given their state with .with_state() to become Router<()>, and merged into the Router<()> parent. Each router keeps its own state, and the final application serves both. This pattern isolates state and can simplify large applications.

State type mismatches cause compile errors:

If you try to nest a child router that expects a different state type without calling .with_state() on it, the Rust compiler will report a trait bound error. This is a common beginner frustration. Always ensure that either the state types match exactly or the child router has already had its state set.

Combining nest with Fallbacks

Axum's nest method does not alter how fallback routes work, but it is important to understand the interaction. A fallback route is used when no route matches the incoming path. If you set a fallback on the parent router, it will handle all unmatched paths, including those under nested prefixes that do not match any child route. If you set a fallback on the child router, that fallback will only be used for unmatched paths under the child's prefix.

Consider this setup:

use axum::{Router, routing::get, http::StatusCode};
async fn parent_fallback() -> (StatusCode, &'static str) {
    (StatusCode::NOT_FOUND, "Parent fallback")
}
async fn child_fallback() -> (StatusCode, &'static str) {
    (StatusCode::NOT_FOUND, "Child fallback")
}
async fn hello() -> &'static str {
    "Hello"
}
#[tokio::main]
async fn main() {
    let api_router = Router::new()
        .route("/hello", get(hello))
        .fallback(child_fallback);
    let app = Router::new()
        .nest("/api", api_router)
        .fallback(parent_fallback);
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

What happens when you request different paths?

  • GET /api/hello → "Hello"
  • GET /api/missing → "Child fallback" (because the path starts with /api, the child router handles it and its fallback responds)
  • GET /other → "Parent fallback" (because it does not start with /api, the parent's fallback responds)

This behavior is intuitive: the most specific fallback wins. However, note that if the child router has no fallback, the parent's fallback will be used for unmatched paths under the prefix. This can be useful or surprising depending on your intent.

Fallbacks and nest are separate concerns:

The nest method only combines routes; it does not merge fallback handlers. Fallback behavior is determined by the router that ends up handling the unmatched request. If you want a consistent fallback across all nested routers, set it on the parent only and leave children without fallbacks.

Common Mistakes with nest

Even experienced developers sometimes trip over the details of nest. Here are the most frequent pitfalls and how to avoid them.

Using the Wrong Path Prefix

A very common error is misjudging what the final URL will be. Always ask: what does the child router see? It sees the request path after the prefix and exactly one leading slash have been removed. For example:

  • nest("/api", child) and child route /users → final path /api/users
  • nest("/api/", child) and child route /users → final path /api/users (a trailing slash on the prefix is tolerated for the normal case, but a double slash in the request path, like /api//users, does not match - Axum does not normalize slashes)
  • nest("/api", child) and child route / → final path /api exactly
  • nest("/api", child) and child route /users/ → final path /api/users/ (requires trailing slash)

To verify your routes, it can be helpful to temporarily add a handler that returns the original URI or matched path to see what the router received.

Forgetting That nest Merges Routes

When you nest two different routers under the same prefix, their routes are all merged into the parent. If you later add a route to the parent with the same path as one in the child, there can be a conflict. Axum resolves overlapping routes based on specificity (static routes win over parameters), but duplicate exact routes will cause a panic at runtime when the router is built.

To avoid this, organize your routes clearly and avoid nesting routers that intentionally define the same path.

State Type Confusion

As mentioned earlier, state type mismatches are a compile error. The error message can be long and intimidating. The solution is often to add .with_state() to the child router before nesting, or to make the child router generic over the same state type as the parent. Make sure you understand which approach fits your architecture.

Prefix Contains a Wildcard

The nest method expects a path prefix without wildcards or catch-all segments. You cannot use nest("/files/{*path}", ...) because wildcards are not allowed in nest prefixes - registering one panics with Invalid route: nested routes cannot contain wildcards (*). The same rule applies to nest_service: a wildcard prefix panics there too. For regular routers, keep the prefix simple: static segments and possibly parameters, but no wildcards.

Practical Use Cases

The nest method shines in real-world applications. Here are some scenarios where it makes code significantly cleaner.

API Versioning

When you need to support multiple versions of your API, nesting the same base router under different prefixes is a clean pattern.

use axum::{Router, routing::get};
async fn list_users_v1() -> &'static str { "v1 users" }
async fn list_users_v2() -> &'static str { "v2 users" }
fn api_v1() -> Router {
    Router::new()
        .route("/users", get(list_users_v1))
}
fn api_v2() -> Router {
    Router::new()
        .route("/users", get(list_users_v2))
}
let app = Router::new()
    .nest("/api/v1", api_v1())
    .nest("/api/v2", api_v2());

This keeps each version's logic separate and makes it trivial to add or remove a version.

Feature Modules

Large applications often organize code by feature: authentication, billing, notifications. Each feature can be a module that exports a Router, and the main router nests them under their respective top-level paths.

use axum::Router;
mod auth {
    use axum::{routing::get, Router};
    async fn login_form() -> &'static str { "login" }
    async fn logout() -> &'static str { "logout" }
    pub fn router() -> Router {
        Router::new()
            .route("/login", get(login_form))
            .route("/logout", get(logout))
    }
}
mod billing {
    use axum::{routing::{get, post}, Router};
    async fn plans() -> &'static str { "plans" }
    async fn subscribe() -> &'static str { "subscribed" }
    pub fn router() -> Router {
        Router::new()
            .route("/plans", get(plans))
            .route("/subscribe", post(subscribe))
    }
}
let app = Router::new()
    .nest("/auth", auth::router())
    .nest("/billing", billing::router());

This modularity makes it easier to test individual features and to assign different maintainers to different parts of the codebase.

Admin and Public Sections

Separating admin routes from public routes is a natural use of nest. Admin routes might require additional middleware or authentication, which can be applied to the nested router as a whole.

use axum::{Router, routing::get, http::Request, middleware::{self, Next}, response::Response};
async fn admin_dashboard() -> &'static str { "dashboard" }
async fn admin_list_users() -> &'static str { "admin users" }
async fn public_home() -> &'static str { "home" }
async fn require_admin_auth(request: Request<axum::body::Body>, next: Next) -> Response {
    // Check the request for admin credentials here; this stub lets it through.
    next.run(request).await
}
let admin_router = Router::new()
    .route("/dashboard", get(admin_dashboard))
    .route("/users", get(admin_list_users))
    .layer(middleware::from_fn(require_admin_auth));
let app = Router::new()
    .nest("/admin", admin_router)
    .route("/", get(public_home));

Because nest merges routes into the parent, any middleware applied to the child router before nesting will still be active for those routes. This is a powerful way to apply guards only to a subset of endpoints.

A Step-by-Step Exercise: Building a Modular API with nest

To solidify your understanding, let's walk through building a small but complete modular API using nest. We'll create three modules: users, posts, and comments, each with its own router, and then combine them under an /api prefix.

1

Step 1: Define the user module router

Create a function that returns a Router for user endpoints. For now, just a couple of simple handlers.

use axum::{Router, routing::get, extract::Path};
async fn list_users() -> &'static str {
    "List all users"
}
async fn get_user(Path(id): Path<String>) -> String {
    format!("User {}", id)
}
fn user_router() -> Router {
    Router::new()
        .route("/", get(list_users))
        .route("/{id}", get(get_user))
}
2

Step 2: Define the post module router

Similar structure for posts, but include a nested route for comments later.

use axum::{Router, routing::get, extract::Path};
async fn list_posts() -> &'static str {
    "List all posts"
}
async fn get_post(Path(id): Path<String>) -> String {
    format!("Post {}", id)
}
fn post_router() -> Router {
    Router::new()
        .route("/", get(list_posts))
        .route("/{id}", get(get_post))
}
3

Step 3: Define the comment module router

This router will be nested under posts to handle comments for a specific post.

use axum::{Router, routing::get, extract::Path};
async fn list_comments(Path(post_id): Path<String>) -> String {
    format!("Comments for post {}", post_id)
}
fn comment_router() -> Router {
    Router::new()
        .route("/", get(list_comments))
}
4

Step 4: Combine everything into the main application

Now assemble the routers: comment router nested inside post router under /{post_id}/comments, post router under /posts, user router under /users, and all of them under /api.

use axum::Router;
#[tokio::main]
async fn main() {
    let api_router = Router::new()
        .nest("/users", user_router())
        .nest("/posts", post_router()
            .nest("/{post_id}/comments", comment_router())
        );
    let app = Router::new()
        .nest("/api", api_router);
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

After following these steps, you have a clean, hierarchical route structure:

  • GET /api/users → list users
  • GET /api/users/1 → get user 1
  • GET /api/posts → list posts
  • GET /api/posts/5 → get post 5
  • GET /api/posts/5/comments → list comments for post 5

The final code is much easier to read and extend than if all routes were listed on one router with full paths repeated.

If your server starts and responds to the above paths, your nest usage is correct:

Run the program and test each URL with curl or a browser. If every route responds as expected, you have successfully used nest to build a modular API. If you get 404s, double-check that your prefixes and child route paths match the examples exactly.

How nest Differs from merge

While this page focuses on nest, it is worth a one-sentence clarification because the two methods are often confused. nest adds a path prefix to all routes of the child router. merge combines routes from another router without any prefix, effectively flattening them into the parent. If you want to group routes but expose them at the same path level, merge is the tool. If you want them under a common path segment, use nest.

For now, keep in mind that nest is about path hierarchy and modularity.

Summary

The nest method is a cornerstone of maintainable Axum applications. It allows you to break a large route table into smaller, reusable routers and mount them under meaningful path prefixes. Key points to remember:

  • nest takes a prefix and a child router, and merges the child's routes with the prefix.
  • Prefixes can include path parameters, which are shared with child handlers.
  • Nesting can be multiple levels deep, and state can be shared or isolated.
  • Fallbacks behave predictably based on which router handles the unmatched request.
  • You cannot nest at the root: nest("/", child) panics with Nesting at the root is no longer supported. Use merge instead. - use merge when there is no prefix to add.
  • The most common mistakes involve path prefix confusion, state type mismatches, and forgetting that child routes are relative to the child's root.

With this understanding, you can now structure your Axum applications in a clean, modular way. The next logical step in your learning is to explore the nest_service method for mounting services like static file serving under a prefix, but that is a separate topic. For now, practice building nested routers with your own handlers and observe how the full URLs are formed.