route_layer in Axum

How route_layer attaches middleware only to routes that match, why 404 and 405 responses stay intact, and how it differs from layer and the method-router forms

What route_layer is

route_layer attaches middleware to routes, but only to routes that actually match the incoming request. That single condition is the whole idea. Everything else on this page follows from it.

Middleware is code that runs before or after a handler. A handler is the function that answers a request. An auth check is middleware. It looks at the request, decides whether the caller may proceed, and either passes the request on to the handler or answers early with a refusal such as 401 Unauthorized. The question route_layer answers is not what the middleware does. The question is when it runs at all. It runs only when a route matched.

That distinction matters most for middleware that can refuse a request early. Picture an API with a private route and a mistyped URL. A request to the private route without a token should get a 401. A request to a path that does not exist should get a 404 Not Found. If the auth middleware runs on every request, including requests to paths that do not exist, the mistyped URL gets a 401 instead of a 404. The client learns nothing about whether the path exists, and anyone reading the logs sees a failed login where there was only a typo. route_layer fixes that. The auth middleware runs only when a route matched, so unknown paths still return 404 and wrong-method requests still return 405 Method Not Allowed.

A useful way to picture it: route_layer wraps the routes, not the router. The router still does its own job first. It matches the path and the method, or it answers 404 or 405 on its own. Only after a match does the middleware get a turn.

The smallest example, auth on one private route

Start with the smallest program that shows the behaviour. One route, one auth middleware, attached with route_layer.

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

async fn hello() -> &'static str {
    "hello"
}

async fn require_auth(request: Request, next: Next) -> Result<Response, StatusCode> {
    if request.headers().contains_key("authorization") {
        Ok(next.run(request).await)
    } else {
        Err(StatusCode::UNAUTHORIZED)
    }
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/private", get(hello))
        .route_layer(middleware::from_fn(require_auth));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
Cargo.toml
[package]
name = "route-layer-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }

require_auth is a middleware function written with from_fn, which turns an async function into middleware. It takes the request and a value called Next. Next represents everything after this middleware, including the handler. If the request carries an authorization header, the middleware calls next.run(request) and returns whatever the handler answers. If the header is missing, it returns Err(StatusCode::UNAUTHORIZED) without ever calling the handler. Returning early like this is called short-circuiting. The handler never runs, and the client gets the 401 straight from the middleware.

route_layer is called after the route call, and that order is part of the meaning. The layer wraps the routes that already exist. Run the server with cargo run and try three requests:

curl http://localhost:3000/private
curl -H "authorization: token" http://localhost:3000/private
curl http://localhost:3000/nope

The first request has no token, so the middleware refuses it and the answer is 401 Unauthorized. The second request carries a token, so the middleware passes it on and the handler answers 200 OK with the body hello. The third request goes to a path with no route, and the answer is 404 Not Found. The auth middleware never ran for that request. There was no route to protect, so there was nothing for the middleware to do.

Three answers that prove the setup works:

If your server answers 401 for the first request, 200 with hello for the second, and 404 for the third, route_layer is doing its job. The 404 on the unknown path is the result that matters most. It is the behaviour this whole page is about.

The same auth attached with layer, and the 404 disappears

Now change exactly one thing in the program above. Replace .route_layer(...) with .layer(...) on the router:

src/main.rs
let app = Router::new()
    .route("/private", get(hello))
    .layer(middleware::from_fn(require_auth));

Everything else stays the same. The middleware function is unchanged, the route is unchanged, and the two good requests behave exactly as before. Only the unknown path changes. GET /nope without a token now returns 401 Unauthorized instead of 404 Not Found.

The reason is the attachment point. The layer method wraps the whole router, including its fallback. The fallback is the answer the router gives when no route matches, which by default is a plain 404. With layer, the auth middleware sits outside the fallback, so every request passes through it first, matched or not. With route_layer, the middleware sits inside the routing decision, so unmatched requests never reach it.

RequestWith route_layerWith layer
GET /private without a token401 Unauthorized401 Unauthorized
GET /private with a token200 OK200 OK
GET /nope without a token404 Not Found401 Unauthorized

The table shows that the two methods agree everywhere except on unmatched paths. That one row is the entire difference, and it is the reason both methods exist. Use layer when a policy genuinely covers everything, including unmatched paths. Logging is the classic case: the requests that hit a 404 are often the ones worth seeing in the log. Use route_layer when a policy must only apply where a handler would otherwise have run.

A 401 on an unknown path is a bug, not a feature:

When auth is attached with the layer method, every mistyped URL in an API returns 401 instead of 404. Clients debugging a wrong path chase a token problem that does not exist. Attach auth with route_layer so that 404 responses stay 404 responses.

Rule 1, only routes added before the call are wrapped

route_layer applies to every route that already exists in the router when it is called. It does not apply to only the most recent route, and it does not apply to routes added later. Read the call as "wrap everything so far". This fragment uses the same hello and require_auth from the first example:

src/main.rs
use axum::{middleware, routing::get, Router};

let app = Router::new()
    .route("/a", get(hello))
    .route_layer(middleware::from_fn(require_auth)) // wraps /a only
    .route("/b", get(hello));                       // /b is NOT protected

Here /a requires a token and /b does not, because /b was added after the route_layer call. A request to /a without a token gets a 401. A request to /b without a token gets a 200 with hello. The program builds without complaint. The router does not warn that /b escaped the layer. That silence is what makes this the most common mistake with route_layer.

The fix is ordering in the code, not a setting. Finish adding routes first, then call route_layer. When a new route is added later, add it above the route_layer call, never below it. Read the router from top to bottom before running it and check that every route the layer should cover sits above the call.

A second route_layer call re-wraps the same routes. The last call ends up outermost, which means it sees the request first. Calling route_layer(A) and then route_layer(B) makes a request meet B first, then A, then the handler. The stacking order is covered in full further down this page.

A route added after the call escapes the layer silently:

This is a runtime silence, not a compile error. The program builds, the route answers, and the middleware never runs for it. If a protected route suddenly stops asking for a token, check whether it sits below the route_layer call.

Rule 2, it only runs when a route matches

The rule from the opening section deserves its own example, because auth is not the only middleware that short-circuits. Maintenance mode is another. A maintenance layer answers 503 Service Unavailable for every request it sees, so that users get a maintenance page instead of the real site. Attached with the layer method, it would also answer 503 for mistyped URLs. Attached with route_layer, unknown paths still return 404 and only real routes show the maintenance page.

src/main.rs
use axum::{
    extract::Request,
    http::StatusCode,
    middleware::{self, Next},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use std::sync::atomic::{AtomicBool, Ordering};

static MAINTENANCE: AtomicBool = AtomicBool::new(false);

async fn hello() -> &'static str {
    "hello"
}

async fn maintenance(req: Request, next: Next) -> Response {
    if MAINTENANCE.load(Ordering::SeqCst) {
        (StatusCode::SERVICE_UNAVAILABLE, "Down for maintenance").into_response()
    } else {
        next.run(req).await
    }
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/private", get(hello))
        .route_layer(middleware::from_fn(maintenance));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

MAINTENANCE is a shared on-off switch. AtomicBool is a boolean value that many requests can read and change safely at the same time. Ordering::SeqCst is the strictest memory ordering, which is the safe default when a beginner is unsure which ordering to pick. In a real program the switch would be flipped by an admin endpoint or a config reload. Here the point is the routing behaviour: while the switch is off, /private answers 200. While it is on, /private answers 503 with the maintenance text. And /nope answers 404 in both cases, because the maintenance middleware never runs for a request that matched nothing.

The switch is a static value, outside any function, for a mechanical reason. In axum 0.8, the layer is applied fresh for each request on normal routes, so any state stored inside the middleware service itself does not survive from one request to the next. State that must be shared across requests has to live outside the service, behind a shared handle such as a static or an Arc. An Arc is a reference-counted pointer that lets several owners share one value. The static here plays the same role in the simplest possible way.

The same reasoning covers a feature-flag layer that refuses requests for a disabled feature, and a maintenance layer of any shape. The general principle: any middleware whose response replaces the handler response belongs on route_layer, so that the replacement only happens where a handler would otherwise have run.

Short-circuiting is the test for choosing route_layer:

Ask one question about a middleware: can it answer without calling the handler? Auth can, maintenance mode can, a feature flag can. If the answer is yes, the middleware is a candidate for route_layer. Middleware that only observes traffic, such as logging, cannot short-circuit, so the question does not apply to it.

Rule 3, it panics on an empty router

Calling route_layer before any route has been added is a programming error, and axum treats it as one. The call panics at runtime with the message "Adding a route_layer before any routes is a no-op. Add the routes you want the layer to apply to first."

src/main.rs
// PANICS at runtime: no routes exist yet.
let app: Router = Router::new().route_layer(middleware::from_fn(require_auth));

The panic is deliberate. A route_layer call with no routes to wrap would silently do nothing, and silent no-ops are how auth ends up missing from a route. If this panic appears, the route_layer call was almost certainly written before the route calls. Move it after them.

route_layer panics, layer does not:

The layer method on an empty router is fine, because it always has something to wrap: the fallback. route_layer on an empty router panics, because with no routes there is nothing for it to wrap. The asymmetry is intentional: a route_layer call with no routes would be a no-op, and silent no-ops are how auth ends up missing.

One path, one method check, MethodRouter route_layer and the 405

route_layer also exists on MethodRouter, and there it protects a second status code. A MethodRouter is what get(handler) or post(handler) returns. It matches one path, possibly for several methods. MethodRouter::route_layer runs the middleware only when the path matches and the method is one the router handles. A request with the wrong method keeps its 405 Method Not Allowed instead of being turned into a 401. Here is the complete program, with the same hello handler and require_auth middleware as the first example:

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

async fn hello() -> &'static str {
    "hello"
}

async fn require_auth(request: Request, next: Next) -> Result<Response, StatusCode> {
    if request.headers().contains_key("authorization") {
        Ok(next.run(request).await)
    } else {
        Err(StatusCode::UNAUTHORIZED)
    }
}

#[tokio::main]
async fn main() {
    let app = Router::new().route(
        "/foo",
        get(hello).route_layer(middleware::from_fn(require_auth)),
    );

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The Cargo.toml is the same as the first example on this page. Run it and try three requests:

curl http://localhost:3000/foo
curl -H "authorization: token" http://localhost:3000/foo
curl -X POST http://localhost:3000/foo

The behaviour is:

  • GET /foo without a token returns 401 Unauthorized. The path and the method both matched, so the auth middleware ran and refused the request.
  • GET /foo with a token returns 200 OK.
  • POST /foo without a token returns 405 Method Not Allowed, not 401. The path matched but the method did not, so the auth middleware never ran.

Compare that with MethodRouter::layer, which wraps the method router itself. A wrong-method request still passes through that layer on its way to the 405. The two methods look alike and differ exactly here. route_layer is matched-only. layer is per-path. If tests assert a 405 for a wrong method, the middleware on that path needs route_layer.

Three tools that look alike

Three attachment points look similar enough to confuse, and each one answers a different question about coverage. The table below names them side by side. Read it as a chooser, not as a list to memorise.

Attachment pointCoversRuns on a non-matching request?Use when
Router::route_layerEvery route added before the callNo, only on a matchA policy shared by a group of routes, such as auth for an admin area
MethodRouter::route_layerOne path, matched method onlyNo, a wrong method keeps its 405A policy on one endpoint where the 405 must survive
MethodRouter::layerAll methods on one pathYes, including wrong-method requestsA policy belonging to one endpoint across its methods, such as a body limit or a timeout for that endpoint

The choice is always the same question: must a non-matching request still pass through this middleware? If the answer is no, use a route_layer form. If the answer is yes, use a layer form. A body limit answers yes, because the limit is about the endpoint itself, not about whether the request should be allowed in. Auth answers no, because a refusal must never rewrite the answer to "does this path exist?".

The same choice appears with ready-made layers, not only with hand-written middleware. Tower-http ships a layer that checks a header value, which is the value of one named header on the request. It can be attached with route_layer exactly like the hand-written auth above:

src/main.rs
use axum::{routing::get, Router};
use tower_http::validate_request::ValidateRequestHeaderLayer;

async fn hello() -> &'static str {
    "hello"
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/foo", get(hello))
        .route_layer(
            ValidateRequestHeaderLayer::has_header_value("authorization", "Bearer password")
                .expect("the header name and value are valid"),
        );

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
Cargo.toml
[package]
name = "route-layer-validate-header"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower-http = { version = "0.7", features = ["validate-request"] }

ValidateRequestHeaderLayer::has_header_value("authorization", "Bearer password") builds a layer that accepts only requests whose Authorization header is exactly Bearer password. A request with that header gets 200 OK. A request with a different token gets 403 Forbidden. A request to an unknown path gets 404 Not Found, because the layer is attached with route_layer and never runs for unmatched requests. The validate-request feature must be enabled in Cargo.toml, or the import fails to compile. The constructor returns a Result because the header name and value are validated, so the example unwraps it with expect.

The ready-made layer and the hand-written one obey the same rules:

ValidateRequestHeaderLayer is a layer like any other. Attached with route_layer it runs only on a match. Attached with the layer method it would run on unmatched requests too, and the same masking of the 404 would appear. The attachment point decides the behaviour, not the layer.

Stacking route_layer calls and mixing with layer

A second route_layer call re-wraps the same routes, and the last call ends up outermost. Outermost means it sees the request first and the response last, like the outer skin of an onion. A small recorder makes the order visible. Each middleware appends its own name to a response header called x-passed, so the finished response shows the order the middleware touched it on the way back out.

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

async fn hello() -> &'static str {
    "hello"
}

async fn tag_a(req: Request, next: Next) -> Response {
    let mut res = next.run(req).await;
    res.headers_mut().append("x-passed", "inner-a".parse().unwrap());
    res
}

async fn tag_b(req: Request, next: Next) -> Response {
    let mut res = next.run(req).await;
    res.headers_mut().append("x-passed", "outer-b".parse().unwrap());
    res
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/x", get(hello))
        .route_layer(middleware::from_fn(tag_a))
        .route_layer(middleware::from_fn(tag_b));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

tag_a is added first, so it is the inner layer. tag_b is added second, so it is the outer layer. On the way in, the request meets tag_b first, then tag_a, then the handler. On the way back out, the response meets tag_a first, then tag_b. Each middleware appends its name to the x-passed header as the response passes it, so the finished response carries the headers in this order:

x-passed: inner-a
x-passed: outer-b

The order looks backwards until the two directions are separated. The request order is outer first. The response order is inner first. The header list shows the response order, because headers are added while the response travels back out.

Mixing layer and route_layer follows the same rule, because each call wraps the router as it exists at that moment. The program below is the same as the one above except for the last two lines: the route layer is added first, then the router layer.

src/main.rs
let app = Router::new()
    .route("/x", get(hello))
    .route_layer(middleware::from_fn(tag_a))
    .layer(middleware::from_fn(tag_b));

The layer call wraps everything, including the already route-layered routes, so tag_b is outermost. A request meets tag_b first, then tag_a. The response still meets tag_a first, so the x-passed header order is the same as before: inner-a, then outer-b. The practical rule is to decide the execution order first, which layer must see the request first, and then write the calls so the outermost layer is added last.

Runs after routing, URI rewriting does not change the route

One more property is shared with the layer method: middleware attached with route_layer runs after routing. By the time the middleware sees the request, axum has already decided which route matched. A middleware that rewrites the request URI cannot change that decision.

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

async fn hello() -> &'static str {
    "hello"
}

async fn rewrite(mut req: Request, next: Next) -> Response {
    *req.uri_mut() = "/hello".parse().unwrap();
    next.run(req).await
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/hello", get(hello))
        .route_layer(middleware::from_fn(rewrite));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request to /old still returns 404. The middleware never runs for that request, so the rewrite never happens. Routing already happened: the router looked at /old, found no route, and the middleware only ever runs when a route has already matched. The rewrite inside it changes the URI the handler sees, not the route that was chosen. The same holds for the layer method: a rewrite there cannot make an unmatched request match either, because routing happened before the layer ran.

When a renamed path must keep working, register the old path as a route instead. Add a second route for the old path, or put a handler on the old path that answers with a redirect to the new one. A layer that rewrites URIs looks like it should work and silently does not, which is worse than a compile error.

Common mistakes

  • Adding routes after the route_layer call. The later routes are unprotected, silently. Finish all route calls first, then call route_layer.
  • Using the layer method for auth. The auth middleware wraps the fallback, so unknown paths return 401 instead of 404. Use route_layer for anything that can refuse a request early.
  • Expecting route_layer to cover the fallback. It cannot, by design. When middleware genuinely must run on unmatched requests, a catch-all logger for example, that is what the layer method is for. The two methods are complements, not substitutes.
  • Calling route_layer before any route exists. It panics. Move the call after the first route.
  • Confusing MethodRouter::route_layer with MethodRouter::layer. The first preserves 405 responses. The second does not. When tests assert a 405 for a wrong method, the middleware needs route_layer.
  • Rewriting the URI inside a route_layer middleware to change routing. Routing already happened. The rewrite changes what the handler sees, not which route was chosen.

Summary

route_layer is the "only if this route matched" attachment point, and the decision framework for the whole page is a single question asked twice. First, can this middleware refuse a request without calling the handler? If yes, it belongs on a route_layer form, so that a 401 or a 503 never replaces a 404. Second, how wide is the coverage: a group of routes, one path with its methods, or one path with the 405 preserved? A group takes the router form, one path takes the method-router form with layer when wrong-method requests must still pass through, and one path with the 405 preserved takes the method-router form with route_layer. Everything else, the order rules, the panic, the stacking order, the fact that routing happens first, is a consequence of that one matched-only condition. Once the condition is clear, the method chooses itself.