Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 38 ยท Routers and Handlers

Axum Fallbacks, 404 and 405 Responses

Customize what Axum answers when no route matches: Router::fallback, method_not_allowed_fallback, the Allow header, JSON 404s, fallback_service and nested fallbacks.

Sooner or later a client asks for something that does not exist: a mistyped URL, an old link, a bot probing for /wp-login.php. By default Axum answers 404 Not Found with an empty body, and when the path exists but the method does not, 405 Method Not Allowed. Those defaults are correct but unfriendly. API clients want a JSON error, and web pages want a proper "page not found" screen.

This lesson shows how to replace both defaults, how fallbacks interact with nested routers, and how to serve a single-page app from the same router.

The default behaviour

Rust
use axum::{routing::get, Router};

let app = Router::new().route("/hello", get(|| async { "hi" }));
  • GET /hello gives 200 and hi.
  • GET /nope gives 404 with no body.
  • POST /hello gives 405 with an allow: GET,HEAD header and an empty body. (Axum adds HEAD for you wherever you register GET.)

The Allow header is not decoration: HTTP says a 405 must list the methods the resource supports. Axum builds it from the routes you registered.

A custom 404 with fallback

fallback takes any handler. It runs for every request that no route matched:

Rust
use axum::{http::{StatusCode, Uri}, response::IntoResponse, routing::get, Json, Router};
use serde_json::json;

async fn not_found(uri: Uri) -> impl IntoResponse {
    (
        StatusCode::NOT_FOUND,
        Json(json!({ "error": "not_found", "path": uri.path() })),
    )
}

fn app() -> Router {
    Router::new()
        .route("/hello", get(|| async { "hi" }))
        .fallback(not_found)
}

Notice that the fallback is a normal handler: it can use extractors (here Uri) and return anything that implements IntoResponse. You must set the status yourself. A fallback that returns just a string answers 200 OK, which makes monitoring and search engines believe the page exists. This is the most common fallback mistake.

A custom 405 with method_not_allowed_fallback

When a route matches the path but not the method, Axum calls the router's method-not-allowed fallback if you set one:

Rust
use axum::{http::StatusCode, routing::get, Router};

async fn wrong_method() -> (StatusCode, &'static str) {
    (StatusCode::METHOD_NOT_ALLOWED, "that method is not supported here")
}

let app = Router::new()
    .route("/hello", get(|| async { "hi" }))
    .method_not_allowed_fallback(wrong_method);

Check the version of Axum you use before relying on this method: it was added in the 0.8 line. If you cannot use it, you can set a fallback on an individual MethodRouter: get(h).fallback(other). That handler runs for any other method on that path. When you replace the default 405 yourself, remember to keep sending an Allow header.

Fallbacks and nested routers

Fallbacks are scoped. Given:

Rust
let api = Router::new()
    .route("/users", get(list_users))
    .fallback(api_not_found);        // JSON errors inside /api

let app = Router::new()
    .nest("/api", api)
    .fallback(html_not_found);       // everything else
  • GET /api/missing is handled by api_not_found, because the request reached the nested router.
  • GET /missing is handled by html_not_found.

If a nested router has no fallback of its own, it uses the one of the router it was nested into. That means a single app.fallback(...) at the top is usually enough, and you only add an inner one when a section needs different behaviour, such as JSON for /api and HTML for pages.

fallback_service: serve files or a single-page app

fallback_service accepts a Tower service instead of a handler. With tower-http this gives the classic setup: the API on /api/*, real files from dist/, and index.html for every other path so the browser router can take over.

Rust
use tower_http::services::{ServeDir, ServeFile};

let spa = ServeDir::new("dist").fallback(ServeFile::new("dist/index.html"));

let app = Router::new()
    .nest("/api", api())
    .fallback_service(spa);

Be careful here: because the SPA service answers everything else, a mistyped /api/uers is caught by the nested api router's fallback (404 JSON), not by the SPA, which is the behaviour you want. A request for /app/settings falls through to index.html.

Stand-in: a router with fallbacks

The first model dispatches in the same order Axum does: exact route and method, then a 405 with an Allow list if the path exists, then the fallback of the innermost router that was entered. Everything is plain Rust; handlers are simple enums standing in for handler functions.

Rust Stand-in: 404, 405 and the Allow header

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Look at the allow value for /hello in the plain router: it lists DELETE, GET and HEAD, built from what was registered. The last line shows why forgetting the status in a fallback is a bug.

Stand-in: nested fallbacks and inheritance

Now the scoping rule. Each router has an optional fallback; a request first walks into the nested router whose prefix matches, and the innermost fallback available wins.

Rust Stand-in: which fallback answers?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

/admin/missing shows inheritance: /admin has no fallback of its own, so it uses the outer html_not_found.

Practical advice

  • Always set the status code in a fallback: (StatusCode::NOT_FOUND, ...).
  • Log the path in the fallback at debug level. Rising 404 counts on one path often reveal a broken link or a client bug.
  • Do not reveal internals in the 404 body. A short, stable error code is enough.
  • For an API, return the same error shape as the rest of your errors; the lessons on error handling build a reusable type for that.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Axum answer by default when the path exists but the method does not?

    A 405 is correct when the resource exists, and the Allow header lists the supported methods.
  2. 2. A fallback handler returns only the string "page not found". What status does the client see?

    A plain string response is 200 OK. A fallback must set StatusCode::NOT_FOUND itself.
  3. 3. A nested router has no fallback of its own. Which fallback handles a miss inside its prefix?

    Nested routers without their own fallback use the outer router's fallback.
  4. 4. Which method serves a single-page app for every path not matched by routes?

    fallback_service takes a Tower service, and ServeDir can fall back to index.html.

Summary

  • Unmatched paths give 404 and wrong methods give 405 with an Allow header; both can be replaced.
  • fallback(handler) is an ordinary handler: use extractors, and set the status code yourself.
  • fallback_service mounts a Tower service, such as ServeDir, for files or a single-page app.
  • Fallbacks are scoped: nested routers use their own, otherwise the outer router's.

Next: Path and Query Extractors