# How do I customise the 404 and 405 responses in axum?
Source: https://ruststudio.org/community/t/169/how-do-i-customise-the-404-and-405-responses-in-axum
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, axum 0.8.9, tokio 1.54.1, tower 0.5.3, Windows 11; handlers called in-process with tower's oneshot
Category: Help and questions | Kind: FAQ | Tags: axum, routing, errors, json | Views: 0

## Short answer
Router::fallback sets the handler for paths that match no route, and Router::method_not_allowed_fallback sets the handler for a known path called with the wrong method. Both take an ordinary handler, so they can return the same JSON error shape as the rest of the API.

## Answer
## 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:

```rust title=src/main.rs
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));
    }
}
```

```text
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)
