Route precedence when paths overlap
Learn how Axum decides which handler runs when multiple routes could match the same URL path, with static routes winning over dynamic parameters, order independence, and duplicate route errors.
When you register several routes in Axum, more than one of them can sometimes match the same incoming URL. For example, a route for /users/42 and a route for /users/{id} both look like they could handle a request to /users/42. Axum has a clear, deterministic set of rules for choosing one of them. Understanding those rules prevents unexpected 404s, panics, and confusing behavior.
The overlap problem in plain terms
Imagine you have two pieces of paper taped to a wall. One says "If someone asks for /special, show the special page." The other says "If someone asks for any single name, like /alice or /bob, greet them." Those two instructions overlap for the path /special. The first instruction is more specific: it names the exact path. The second instruction is a wildcard that could also match /special.
Axum faces the same decision on every incoming request. It must pick exactly one handler from all the routes you registered. The way it picks is not based on the order you wrote the .route() calls in your code. It is based on how specific each route pattern is.
A first small example
Let's build a tiny Axum app that contains one static route and one parameter route. A static route uses a fixed string like /special. A parameter route uses a placeholder in curly braces, like /{name}, which matches any single path segment.
// src/main.rs
use axum::{Router, extract::Path, response::Html, routing::get};
async fn special_page() -> Html<&'static str> {
Html("This is the special page")
}
async fn name_page(Path(name): Path<String>) -> Html<String> {
Html(format!("Hello, {}!", name))
}
fn create_router() -> Router {
Router::new()
.route("/special", get(special_page))
.route("/{name}", get(name_page))
}
#[tokio::main]
async fn main() {
let app = create_router();
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("listening on http://{}", listener.local_addr().unwrap());
axum::serve(listener, app).await.unwrap();
}
Run this program with cargo run. Then open your browser or use curl to test three different paths:
http://127.0.0.1:3000/special- you will see "This is the special page".http://127.0.0.1:3000/alice- you will see "Hello, alice!".http://127.0.0.1:3000/bob- you will see "Hello, bob!".
The request to /special could have been handled by either route. Axum chose the static one. That is the core rule: a route with a literal, exact path segment wins over a route with a parameter placeholder at the same position.
Static wins over dynamic:
If your static route returns the expected response while the parameter route also exists, Axum is working correctly. The most specific pattern always has priority.
Registration order does not change the result
A common beginner assumption is that routes are checked in the order you write them. In Axum, that is not true. The router builds an internal structure that compares all routes at once, independent of their .route() call order.
Here is the same two routes registered in reverse order. The behavior is identical.
fn create_router() -> Router {
Router::new()
.route("/{name}", get(name_page))
.route("/special", get(special_page))
}
Requests to /special still hit special_page, and /alice still hits name_page. The order you type the .route() calls does not influence precedence.
Why order independence matters:
In many web frameworks, you must register specific routes before wildcard routes. Axum removes that footgun. You can reorganize your routing code for readability without changing behavior.
Exact duplicate routes cause a panic
If you register two routes with the same path and the same HTTP method, Axum cannot decide which one should run. Instead of silently picking one, it panics when you build the router. This panic happens before the server starts, so a test that calls create_router() will catch the problem early.
async fn first_handler() -> Html<&'static str> {
Html("First")
}
async fn second_handler() -> Html<&'static str> {
Html("Second")
}
fn create_router() -> Router {
Router::new()
.route("/duplicate", get(first_handler))
.route("/duplicate", get(second_handler))
}
When this code runs, you will see a panic like this:
Overlapping method route. Handler for 'GET /duplicate' already exists
The meaning is clear: you told Axum two different handlers for the same method and path, and it refuses to guess.
Duplicate route panic:
Registering the same path and method twice is a programming error. It does not produce a compile-time error, but it will panic at runtime when the router is constructed. Always check your route table for accidental duplicates.
Same path with different methods is allowed
The panic only happens when both the path and the HTTP method are the same. You can safely register /special for GET and /special for POST without conflict.
use axum::{Router, response::Html, routing::{get, post}};
async fn get_special() -> Html<&'static str> {
Html("GET on /special")
}
async fn post_special() -> Html<&'static str> {
Html("POST on /special")
}
fn create_router() -> Router {
Router::new()
.route("/special", get(get_special))
.route("/special", post(post_special))
}
A GET /special request runs get_special. A POST /special request runs post_special. This is standard REST API design and does not trigger any precedence conflict, because the method is part of the route's identity.
Catch-all routes are less specific than static routes
A catch-all route uses a syntax like /{*path}. It matches not just one segment but an entire remaining path, including multiple segments. Because it is extremely broad, Axum gives it lower precedence than both static segments and regular parameter segments.
Consider this router:
async fn static_page() -> Html<&'static str> {
Html("Static page")
}
async fn catch_all(Path(path): Path<String>) -> Html<String> {
Html(format!("Catch-all got: {}", path))
}
fn create_router() -> Router {
Router::new()
.route("/static", get(static_page))
.route("/{*path}", get(catch_all))
}
/static→static_pageruns./anything/else→catch_allruns, withpathequal to"anything/else".
The catch-all never steals a request that a more specific route can handle. This rule makes catch-alls safe to use as a broad fallback for unhandled paths, but they do not replace a proper 404 fallback.
Catch-all vs parameter precedence:
A catch-all route like /{*path} is even less specific than a single-parameter route /{name} - but in practice you cannot register both at the same segment position: a parameter route and a catch-all under the same prefix conflict at that position, and the second registration panics (Insertion failed due to conflict with previously registered route). Choose one shape per path level. Static routes, by contrast, coexist fine with either.
Fallback routes have the lowest priority of all
Axum provides a .fallback() method to define a handler that runs when no regular route matches at all. A fallback is not a route pattern; it is the final safety net. Therefore it has lower priority than any route, including catch-alls.
async fn real_route() -> Html<&'static str> {
Html("Real route")
}
async fn not_found() -> Html<&'static str> {
Html("404 - Nothing here")
}
fn create_router() -> Router {
Router::new()
.route("/real", get(real_route))
.fallback(not_found)
}
When you request /real, real_route runs. When you request /anything-else, not_found runs. Even if you later add a catch-all route, the fallback still only runs if the catch-all does not match - which is rare, because a catch-all matches every path with at least one segment (it does not match the bare /). So fallback is always last.
Fallback vs catch-all:
You rarely need both a catch-all and a fallback. If you want to handle all unknown paths with a custom response, use a catch-all route. If you only want a 404 handler for routes that do not match anything you registered, use .fallback().
How Axum internally decides
Think of Axum's routing like a tree. Each path segment is a node. Literal strings like special are written directly on the node. Parameter placeholders like {name} are written as a wildcard node that matches any single segment. Catch-all placeholders like {*path} are a wildcard that matches everything remaining.
When a request comes in, Axum walks down the tree segment by segment. At each step, it first checks if there is a literal match for the segment. Only if no literal match exists does it try a parameter node. And only if no parameter node exists does it try a catch-all. This is why static beats parameter beats catch-all.
This mental model also explains why registration order doesn't matter: the tree is built from all routes at once, and the comparison happens at request time using the tree's structure.
Testing precedence with unit tests
You can write unit tests that verify the correct handler is chosen. Axum's Router implements tower::Service, so you can send fake requests without starting a real server. Here is an example using tower::ServiceExt and http-body-util.
First, add these dev-dependencies to your Cargo.toml:
[dev-dependencies]
http-body-util = "0.1"
tower = { version = "0.5", features = ["util"] }
Then create a test module in src/tests.rs:
// src/tests.rs
use axum::{body::Body, http::Request, http::StatusCode};
use http_body_util::BodyExt;
use tower::ServiceExt;
use super::*;
#[tokio::test]
async fn static_route_wins_over_param() {
let response = create_router()
.oneshot(Request::builder().uri("/special").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response.into_body().collect().await.unwrap().to_bytes();
let html = String::from_utf8(body.to_vec()).unwrap();
assert_eq!(html, "This is the special page");
}
#[tokio::test]
async fn param_route_handles_other_paths() {
let response = create_router()
.oneshot(Request::builder().uri("/alice").body(Body::empty()).unwrap())
.await
.unwrap();
let body = response.into_body().collect().await.unwrap().to_bytes();
let html = String::from_utf8(body.to_vec()).unwrap();
assert_eq!(html, "Hello, alice!");
}
To run these tests, place mod tests; at the bottom of src/main.rs:
// src/main.rs (bottom)
#[cfg(test)]
mod tests;
The first test proves that /special hits the static handler, not the parameter handler. The second proves that other one-segment paths hit the parameter handler. These tests are fast and do not require a running server.
Tests confirm the rules:
If these tests pass, your understanding of route precedence is correct. Writing a few tests like these is a good way to document your routing intentions and catch accidental regressions.
Common mistakes and how to avoid them
Assuming registration order matters - Many developers coming from other frameworks write their wildcard routes last, thinking that will give them lower priority. In Axum, that habit is harmless but unnecessary. The order is irrelevant; only specificity matters.
Forgetting that a static route will always beat a parameter route - If you add a static route /admin and already have /{page}, requests to /admin will go to the static handler, not the parameter handler. That is usually what you want, but if you expected the parameter handler to see "admin" as the value, you will be surprised. If you need to treat admin as a parameter value in some cases, you must design your routes differently (for example, use a query parameter or a different path structure).
Registering the same path and method twice - This causes a panic. The error message is clear, but you might not realize you have duplicates if you use route merging or nested routers. Always search your code for duplicate .route("/path", get(...)) calls.
Using a catch-all when a parameter route already covers the case - A catch-all /{*path} is extremely broad and can mask routing mistakes. Prefer more specific parameter routes when possible, and reserve catch-alls for truly arbitrary paths.
Silent behavior changes after adding a static route:
Adding a new static route can silently change the behavior of existing parameter routes. Before adding a literal path, check whether any parameter route would have previously captured that path and whether that matters for your application logic.
A real-world scenario
Imagine you are building a blog. You have a route for user profiles like /users/{username}. Later you want a special page for /users/admin that shows a dashboard. You add:
Router::new()
.route("/users/admin", get(admin_dashboard))
.route("/users/{username}", get(user_profile))
Now /users/admin goes to the dashboard, while /users/alice goes to the profile page. This is exactly the static-over-param rule in action. You did not need to change the parameter route or add any special checks inside the handler.
If you later decide that admin should also be a valid username, you have a conflict. The static route always wins, so no user can register the username admin. In a real application, you would either reserve that username at signup time or move the admin dashboard to a different path like /admin.
Route precedence with nested routers
When you use .nest() to group routes under a prefix, the same precedence rules apply within the nested scope. A static segment inside the nested router still beats a parameter segment inside the same nested router. The prefix just adds another layer of literal path before the nested routes.
async fn api_users() -> Html<&'static str> {
Html("API users")
}
async fn api_user_by_id(Path(id): Path<String>) -> Html<String> {
Html(format!("API user {}", id))
}
fn create_router() -> Router {
let api_router = Router::new()
.route("/users", get(api_users))
.route("/users/{id}", get(api_user_by_id));
Router::new()
.nest("/api", api_router)
}
Requests to /api/users hit the static api_users handler. Requests to /api/users/42 hit the parameter handler. The nesting does not alter the static-over-param rule; it only adds a fixed prefix.
Nesting keeps precedence local:
When you nest routers, each nested router resolves its own internal precedence first. If a nested router has no matching route, the outer router's fallback or other routes may handle the request. The overall principle remains: most specific path wins at every level.
Summary
Route precedence in Axum is deterministic and based on specificity, not on registration order. A literal path segment always beats a parameter segment, and a parameter segment beats a catch-all. Exact duplicate routes for the same method and path cause a panic at router construction time. Fallback handlers sit below all regular routes.
The single most important insight from this page is: when two routes overlap, Axum picks the one with more literal, fixed segments. If you keep that rule in mind, you can design clean route tables without wondering which handler will run.
This topic unlocks the ability to safely mix static pages, dynamic resources, and catch-alls in a single application. From here, you can apply the same precedence thinking to method filters and API versioning patterns.