Global Middleware in Axum

What global middleware means in Axum, the two rules that govern it, and how it differs from middleware that runs only when a route matches

What global middleware means

Global middleware is middleware attached to a whole router with the layer method. It wraps every route that was added to the router before the layer call. It also wraps the fallback, which is the handler that answers when no route matches. A request to a path that does not exist still passes through global middleware on its way to the 404 Not Found response.

There is no separate global middleware type. Global middleware is the layer method used at router scope, and the shape below plus the two rules are the whole idea.

The canonical shape

src/main.rs
use axum::{
    extract::Request,
    middleware::{self, Next},
    response::Response,
    routing::get,
    Router,
};

async fn home() -> &'static str {
    "Home page"
}

async fn about() -> &'static str {
    "About page"
}

async fn mark_global(req: Request, next: Next) -> Response {
    let mut res = next.run(req).await;
    res.headers_mut()
        .insert("x-global", "yes".parse().unwrap());
    res
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(home))
        .route("/about", get(about))
        .layer(middleware::from_fn(mark_global));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }

mark_global is a small middleware function that runs the rest of the stack and then stamps an x-global: yes header onto the response. Attached after both routes, it wraps both of them and the fallback, so a request to /, to /about, and to an unknown path all come back carrying the header. A logging layer behaves the same way, it just writes a log line instead of stamping a header, and tracing is the usual reason to attach a layer globally. The marker header is used here because it is visible in the response itself, with no log setup needed to see it.

$ curl -i http://localhost:3000/
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
x-global: yes
content-length: 9
date: Fri, 13 Nov 2026 08:23:04 GMT

Home page

$ curl -i http://localhost:3000/nope
HTTP/1.1 404 Not Found
x-global: yes
content-length: 0
date: Fri, 13 Nov 2026 08:23:04 GMT

The unknown path still answers 404 Not Found, and the x-global header is on that response too. The layer ran even though no route matched.

Seeing the header on a 404 means it is working:

Run the program above and request a path that does not exist, such as /nope. The server answers 404 Not Found, and the response still carries the x-global: yes header. That is the sign the layer is global.

Global is a scope, not a kind of middleware:

Any layer can be attached globally or to a smaller scope. Tracing is usually global, auth is usually matched-only, but nothing in the layer itself decides that. The attachment point decides it.

The two rules

Two rules govern global middleware, and every mistake with it breaks one of them.

Add routes first

The layer method wraps only the routes that already exist when it is called. A route added after the call is not wrapped, and nothing warns you about it. The route works normally, just without the middleware. Write every route call first, then the layer call last, and add any later route above the layer call.

A route added after the layer call runs without the middleware:

This is a runtime silence, not a compile error. The program builds, the route answers, and the middleware never runs for it.

It wraps the fallback too

Global middleware runs on unmatched requests. That is exactly what logging and tracing need: the requests that hit a 404 show mistyped paths and broken links. The same property is exactly wrong for middleware that can refuse a request early. An auth check attached globally turns every mistyped URL into a 401 Unauthorized instead of a 404, because the auth layer runs before the router can say the path does not exist. For anything that can refuse a request, use the matched-only attachment instead, so unknown paths keep their 404.

Global auth hides missing pages:

Auth, feature flags, and maintenance mode all replace the handler answer with their own refusal. Attached globally, they replace the 404 as well.

Summary

Global middleware is the layer method at router scope: every route added before the call, plus the fallback. Add routes first, because anything added after the call escapes the layer silently. Remember that the fallback is included, because that is what makes global middleware right for logging and wrong for auth. If unmatched requests must pass through the middleware, attach it globally. If they must not, attach it where it runs only on a match.