expression

Axum: middleware only for matched routes

Use route_layer after defining the routes when an early rejection should not replace the ordinary not-found response for an unknown path. The example uses a fixed demonstration gate, not an authorization implementation. In-memory standalone Cargo example. Expected stdout (not executed): 403 404 Common mistake: Attaching route_layer before adding routes or expecting it to cover later routes.

Formal Syntax & Structure

rust syntaxrust
Router::route_layer(layer)

Working Example

Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() {    use axum::{routing::get, middleware::{self, Next}, response::{Response, IntoResponse}};    async fn closed(_: axum::extract::Request, _: Next) -> Response { StatusCode::FORBIDDEN.into_response() }    let app = Router::new().route("/known", get(|| async { "ok" })).route_layer(middleware::from_fn(closed));    for path in ["/known", "/unknown"] {        let r = app.clone().oneshot(Request::builder().uri(path).body(Body::empty()).unwrap()).await.unwrap();        println!("{}", r.status().as_u16());    }}
Rust Reference