NestedPath
Learn how to use the NestedPath extractor in Axum to get the prefix a route is nested at.
When you mount a router inside another router using nest, Axum strips the outer prefix before passing the request inward. The NestedPath extractor gives a handler access to the prefix itself - the path the matched route is nested at. For a router nested at /api, NestedPath is "/api". This page explains what NestedPath is, why it is useful, how it behaves at different nesting levels, and shows several complete examples you can run yourself.
What NestedPath Solves
The nest method lets you group routes under a common path prefix. For example, you might nest an API router at /api so that a route defined as /users inside that router actually responds to /api/users. When a request arrives at /api/users/42, the nested router sees /users/42. If a handler inside that router needs to know "under which prefix am I mounted?", the answer is exactly what NestedPath provides: "/api".
Without NestedPath, a handler that builds links or redirects would have to hard-code the prefix. That breaks when the prefix changes or when the same router is reused under a different prefix. NestedPath gives you the prefix the current route is nested at, so handlers stay portable. (If you want the inner path with the prefix removed, that is what the Uri extractor sees inside a nested router - not NestedPath.)
Understanding the Request Flow Through nest
Before looking at code, let's trace what happens to the URL when you nest a router. Suppose you have this setup:
use axum::{Router, routing::get};
async fn users_index() -> String {
"List of users".to_string()
}
let app = Router::new()
.nest("/api", Router::new().route("/users", get(users_index)));
The outer router has a nest at /api. Inside the nested router, there is a route for /users. When a client sends a request to /api/users, Axum performs these steps:
- The outer router sees that the path starts with
/api. - It strips
/apifrom the beginning of the path, leaving/users. - The nested router is called with the remaining path
/users. - The nested router matches
/usersand callsusers_index.
At step 3, the nested router receives /users. The Uri extractor inside the handler would show that stripped path. NestedPath, by contrast, gives you "/api" - the prefix the route is nested at, not the inner path.
Contrast that with the full original path /api/users. If a handler needs the full path as the client saw it, it should use a different extractor (OriginalUri). NestedPath intentionally gives only the prefix, because that is the piece a handler needs to build links and redirects that stay under the same mount point.
A Basic NestedPath Example
Let's write a minimal server that nests a router and uses NestedPath to return the nested path to the client. Create a new Axum project, add the dependencies axum and tokio, and then put this code in main.rs.
// main.rs
use axum::{
Router,
extract::NestedPath,
routing::get,
};
#[tokio::main]
async fn main() {
let app = Router::new()
.nest("/api", Router::new().route("/status", get(show_nested_path)));
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();
}
async fn show_nested_path(path: NestedPath) -> String {
format!("The nested path is: {}", path.as_str())
}
When you run this and visit http://127.0.0.1:3000/api/status, you will see:
The nested path is: /api
If you visit a different nested route, say if you add another one later, NestedPath still shows "/api" - it is the prefix, not the route. The important observation: the prefix /api is exactly what you get, and the inner route (/status) is not part of it.
The NestedPath type is a small wrapper around a string. Call .as_str() on it to get a &str you can print, compare, or join into a longer URL. It has no other methods, and you cannot use it where a String is expected without calling .as_str() first - it only carries the prefix.
Reading Concrete Parameter Values
NestedPath is not a route pattern and not the request path; it is the nest prefix as a plain string. That makes it useful for logging which mount point handled a request, or for building links that stay under the same prefix.
Consider a nested router that serves user profiles. The inner route might be defined as /users/{id}. When a request comes in for /api/users/alice, the nested router sees /users/alice (that is what the Uri extractor would show), and NestedPath returns "/api". Let's see that in action.
// main.rs
use axum::{
Router,
extract::{Path, NestedPath},
routing::get,
};
#[tokio::main]
async fn main() {
let app = Router::new()
.nest("/api", Router::new().route("/users/{id}", get(show_user)));
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();
}
async fn show_user(Path(id): Path<String>, nested: NestedPath) -> String {
format!(
"Request for user '{}' reached nested path: {}",
id,
nested.as_str()
)
}
Visit http://127.0.0.1:3000/api/users/alice. The handler receives two extractors: Path<String> and NestedPath. The output is:
Request for user 'alice' reached nested path: /api
Notice that the Path extractor already gives you the parameter id as alice, while NestedPath gives you the mount prefix /api. If you wanted the inner path /users/alice, that is what the Uri extractor sees inside a nested router - NestedPath never contains route segments or parameter values.
Using NestedPath for Redirects and Link Generation
A common need inside a nested router is to redirect to another route under the same prefix. NestedPath gives you exactly the prefix to build that URL with: prepend it to the new inner path. For example, imagine an API endpoint that redirects from /api/old to /api/new. Inside the handler, NestedPath is /api, so the redirect target is format!("{}/new", nested.as_str()). You do not need a constant for the prefix - NestedPath supplies it, which keeps the handler working even if the router is later mounted under a different prefix.
// main.rs
use axum::{
Router,
extract::NestedPath,
response::Redirect,
routing::get,
};
#[tokio::main]
async fn main() {
let app = Router::new()
.nest("/api", Router::new()
.route("/old", get(redirect_old))
.route("/new", get(|| async { "This is the new page" })));
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();
}
async fn redirect_old(nested: NestedPath) -> Redirect {
Redirect::to(&format!("{}/new", nested.as_str()))
}
When you visit /api/old, the server answers with a 303 See Other status and a Location: /api/new header, and the browser follows it to the new page. The handler never mentions the string "/api" itself: it reads the prefix from NestedPath and appends "/new". If you later remount the same router under /v2, the same handler redirects to /v2/new with no code change. A hard-coded "/api/new" would keep pointing at the old prefix after such a move, which is exactly the mistake NestedPath removes.
Redirect builds the URL from the prefix:
Redirect::to takes the full target path, so the handler must join the prefix and the inner route itself. NestedPath supplies only the first half. Forgetting the inner part would redirect the client to the mount point (/api) instead of the resource (/api/new).
Multiple Levels of Nesting
Axum allows nesting routers inside nested routers. Each nest adds its own prefix, and NestedPath is the full accumulated prefix chain. When you request a path, the innermost router sees only the part that remains after all outer prefixes have been removed - but NestedPath reports the prefixes, not the remainder.
Suppose you have:
- Outer router nests at
/api - Middle router nests at
/v1 - Inner router has route
/users
A request to /api/v1/users will be processed as follows:
- Outer strips
/api, passes/v1/usersto middle. - Middle strips
/v1, passes/usersto inner. - Inner matches
/usersand calls the handler withNestedPathequal to"/api/v1"- the whole prefix chain.
Here is the code:
// main.rs
use axum::{
Router,
extract::NestedPath,
routing::get,
};
#[tokio::main]
async fn main() {
let inner = Router::new().route("/users", get(show_nested));
let middle = Router::new().nest("/v1", inner);
let app = Router::new().nest("/api", middle);
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();
}
async fn show_nested(path: NestedPath) -> String {
format!("Nested path inside /api/v1: {}", path.as_str())
}
Visiting http://127.0.0.1:3000/api/v1/users gives:
Nested path inside /api/v1: /api/v1
NestedPath includes all of the prefixes. It is the mount point of the route, not the remainder of the path. If you need the remainder (/users), that is what the Uri extractor sees inside the nested router. If you need the full path, use OriginalUri or MatchedPath (which gives the pattern), but those are separate topics. For this page, remember: NestedPath is the prefix chain, not the inner path.
NestedPath vs. MatchedPath and OriginalUri
It is common to confuse NestedPath with the other path-related extractors. Here is a quick clarification, but note that each has its own dedicated page if you need deeper detail.
- NestedPath: the prefix the matched route is nested at. For a request to
/api/users/42with nest at/apiand route/users/{id},NestedPathis"/api". - MatchedPath: the route pattern that matched, including any parameter names and the nest prefix. In the same scenario,
MatchedPathwould be"/api/users/{id}". - OriginalUri: the full URI as the client sent it, including query string and scheme if available. It would be
"/api/users/42".
NestedPath is specifically designed for the situation where you have nested routers and want to know the mount prefix of the route that handled the request. If you are not using nest, extracting NestedPath fails - the handler returns a 500 Internal Server Error ("The matched route is not nested").
What Can Go Wrong
The most common mistake when using NestedPath is expecting it to contain the inner path or the full original path. Beginners often assume that "path" means the whole URL path as the browser shows it, or the part after the prefix. But NestedPath is only the nest prefix itself - for a route nested at /api, it is "/api", nothing more. If you need the inner path, use the Uri extractor inside the nested router; if you need the full path, use OriginalUri instead. A handler that builds links from NestedPath alone, without appending the inner route, will produce URLs that point at the mount point rather than the resource.
Another mistake is trying to use NestedPath to obtain route parameter values. NestedPath contains no parameter values at all - for /api/users/alice it is just "/api". For structured data, use the Path extractor. NestedPath gives you a prefix string; parsing it for values is meaningless.
Do Not Use NestedPath for Full URL Construction:
NestedPath only contains the nest prefix. To build a complete URL you must combine it with the inner route path, the scheme, and the host. Using NestedPath alone points at the mount point, not the resource.
A third pitfall arises when you nest a router but the handler is mounted directly on the nested router without a further route. For example:
.nest("/api", Router::new().route("/", get(show_nested)))
A request to /api matches that inner "/" route, and NestedPath is "/api". A request to /api/ does not match - a nested "/" route matches the bare prefix only, so /api/ returns 404. NestedPath itself does not depend on the trailing slash; it is the prefix either way. Always be aware that the trailing slash matters in Axum routing: the inner route "/" matches the bare prefix /api, not /api/.
NestedPath without nesting fails with a 500:
Extracting NestedPath in a handler that is not inside a nested router does not give you an empty string. The extraction fails and the handler returns a 500 Internal Server Error with the message "The matched route is not nested". Only use this extractor in handlers that actually run under a nest call.
Verifying Your Setup Is Correct
When you run one of the examples above and see output that is exactly your nest prefix, your NestedPath usage is correct. You can add a temporary println! inside a handler to print the path during development:
async fn debug_handler(nested: NestedPath) -> String {
println!("NestedPath: {}", nested.as_str());
format!("ok")
}
Everything Works:
If the printed value is your nest prefix, NestedPath is working as intended. For example, nesting at /api and requesting /api/hello should print /api.
Summary
NestedPath solves a specific problem: letting a handler know the prefix it is mounted under, without hard-coding it. It returns the nest prefix (the full prefix chain for multi-level nesting) - for a route nested at /api, it is "/api". This makes handlers more reusable because they do not depend on a hard-coded prefix, and it gives you exactly the piece you need to build links and redirects that stay under the same mount point.
The main takeaway is that NestedPath is the prefix, not the inner path. It tells you where the route is mounted. When you need the inner path as the nested router sees it, use the Uri extractor. When you need the full original URL, choose OriginalUri. When you need the route pattern, choose MatchedPath. And when you need to extract individual parameters, use Path.
Now that you understand NestedPath, you can build nested route structures that log which mount point handled a request, generate links correctly when combined with prefix information, and debug routing issues more easily. The next natural step is to look at how to organize nested routers across multiple files using the routes/mod.rs pattern, which often goes hand-in-hand with NestedPath in larger applications.