expression

Axum: repeated layer ordering

Each layer wraps routes that already exist. With repeated layer calls, the most recently attached layer sees the request first and the response last. Order matters when one layer needs data installed by another. In-memory standalone Cargo example. Expected stdout (not executed): B in A in handler A out B out Common mistake: Reading repeated layer calls as top-to-bottom request execution.

Formal Syntax & Structure

rust syntaxrust
router.layer(a).layer(b)

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};    async fn a(req: axum::extract::Request, next: Next) -> Response {        println!("A in"); let r = next.run(req).await; println!("A out"); r    }    async fn b(req: axum::extract::Request, next: Next) -> Response {        println!("B in"); let r = next.run(req).await; println!("B out"); r    }    let app = Router::new().route("/", get(|| async { println!("handler"); "ok" })).layer(middleware::from_fn(a)).layer(middleware::from_fn(b));    let _ = app.oneshot(Request::new(Body::empty())).await.unwrap();}
Rust Reference