Answer#
By default an unknown path gives 404 with an empty body and a wrong method gives 405 with an empty body. Two router methods replace them:
use axum::{body::{to_bytes, Body}, http::{Request, StatusCode}, response::IntoResponse, routing::get, Json, Router};
use serde_json::json;
use tower::ServiceExt;
async fn home() -> &'static str { "home" }
async fn not_found() -> impl IntoResponse {
(StatusCode::NOT_FOUND, Json(json!({ "error": "no such route" })))
}
async fn wrong_method() -> impl IntoResponse {
(StatusCode::METHOD_NOT_ALLOWED, Json(json!({ "error": "method not allowed" })))
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(home))
.fallback(not_found)
.method_not_allowed_fallback(wrong_method);
for (m, uri) in [("GET", "/"), ("GET", "/missing"), ("POST", "/")] {
let res = app.clone().oneshot(Request::builder().method(m).uri(uri).body(Body::empty()).unwrap()).await.unwrap();
let status = res.status().as_u16();
let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
println!("{m} {uri} -> {status} {}", String::from_utf8_lossy(&body));
}
}GET / -> 200 home
GET /missing -> 404 {"error":"no such route"}
POST / -> 405 {"error":"method not allowed"}fallback returned the 404 body for /missing, and method_not_allowed_fallback the 405 body for POST /. A fallback is a normal handler, so it can use extractors, for example Uri to put the path in a log line.
Common mistakes#
- Letting a fallback answer
200. Return the status explicitly, as the tuple here does; otherwise crawlers and clients treat unknown pages as real.
Related questions#
How do I serve a single-page app for unknown paths?#
Use a file service as the fallback; the thread on static files shows fallback_service.
Sources#
- axum,
Router::fallback: https://docs.rs/axum/0.8.9/axum/struct.Router.html (read 2026-12-05)