Middleware Layer Ordering in Axum With tower-http
Understand how middleware layers run in Axum, why repeated layer calls and ServiceBuilder give opposite orders, and where to place TraceLayer, CompressionLayer, TimeoutLayer, and SetSensitiveHeadersLayer
Add two pieces of middleware to an Axum application and one of them runs first. Add five, and the order they run in decides what each one can see. A logger placed in the wrong spot misses the header it was meant to record. A body limit placed in the wrong spot lets a body be read without a cap. A sensitive-header layer placed in the wrong spot leaks a token into the logs. None of these failures produces an error message. The program compiles, the server runs, and the behaviour is quietly wrong. This page explains the two ordering rules, shows them running with real output, and works through the common tower-http pairs so you can place each layer where it belongs.
What Layer Ordering Means
Middleware in Axum is built on Tower's Layer and Service traits. A layer wraps another service, like a layer of wrapping around a gift. The request passes through the outermost wrapper first, then the next, until it reaches the handler in the middle. The response travels back out in the reverse direction, through each wrapper again.
That picture gives you the two facts that explain everything on this page. A layer that sits outside another layer sees the request before that layer does, and sees the response after it does. A layer that sits inside sees the request later and the response earlier. Every ordering decision is a choice about who sees what, and when.
Axum gives you two ways to apply layers. You can call .layer() repeatedly on a router, or you can compose layers with tower::ServiceBuilder and apply the combined result with one .layer() call. The two ways follow opposite rules, and that is the single most common source of confusion in this area.
Repeated layer Calls, Last Call Outermost
When you call .layer() on a router several times, each call wraps everything built so far. The last .layer() you write becomes the outermost layer. Requests enter through it first, and responses leave through it last.
Here is a small program with three layers that print when they run, built with from_fn, which turns an async function into middleware. Each layer prints a line before the handler runs and a line after.
use axum::{
middleware,
response::Response,
routing::get,
Router,
};
use std::convert::Infallible;
async fn layer_one(
req: axum::extract::Request,
next: middleware::Next,
) -> Result<Response, Infallible> {
println!("layer_one - before handler");
let response = next.run(req).await;
println!("layer_one - after handler");
Ok(response)
}
async fn layer_two(
req: axum::extract::Request,
next: middleware::Next,
) -> Result<Response, Infallible> {
println!("layer_two - before handler");
let response = next.run(req).await;
println!("layer_two - after handler");
Ok(response)
}
async fn layer_three(
req: axum::extract::Request,
next: middleware::Next,
) -> Result<Response, Infallible> {
println!("layer_three - before handler");
let response = next.run(req).await;
println!("layer_three - after handler");
Ok(response)
}
async fn handler() -> &'static str {
println!("handler executed");
"Hello, world!"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(handler))
.layer(middleware::from_fn(layer_one))
.layer(middleware::from_fn(layer_two))
.layer(middleware::from_fn(layer_three));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Each middleware function receives the request and a Next value. Next represents the rest of the stack, including the handler. Calling next.run(req).await passes the request onward and returns the response. The Result<Response, Infallible> return type means the function always succeeds. Infallible is a type that can never hold a value, so returning it says there is no error case at all.
Run the server and send a request to http://127.0.0.1:3000/. The console shows this order.
layer_three - before handler
layer_two - before handler
layer_one - before handler
handler executed
layer_one - after handler
layer_two - after handler
layer_three - after handler
This output was observed live while writing this page. The last layer added, layer_three, runs first on the way in and last on the way out. The first layer added, layer_one, sits closest to the handler and runs last on the way in and first on the way out. The response order is the exact reverse of the request order, which is what the onion picture predicts.
Matching output confirms the rule:
If your console shows layer_three first and layer_one last on the way in, with the reverse on the way out, the layers are stacked as described. If your output is in written order instead, you are probably looking at a ServiceBuilder stack, which follows the opposite rule, covered in the next section.
ServiceBuilder, First Listed Outermost
tower::ServiceBuilder composes several layers into one combined layer. Inside a builder, the layers run in the order you write them, from top to bottom. The first layer listed is the outermost and runs first. That is the opposite of repeated .layer() calls, and it is the reason the two forms are so often confused.
The same three layers, rewritten with a ServiceBuilder, produce the opposite output.
use axum::{
middleware,
response::Response,
routing::get,
Router,
};
use std::convert::Infallible;
use tower::ServiceBuilder;
async fn layer_one(
req: axum::extract::Request,
next: middleware::Next,
) -> Result<Response, Infallible> {
println!("layer_one - before handler");
let response = next.run(req).await;
println!("layer_one - after handler");
Ok(response)
}
async fn layer_two(
req: axum::extract::Request,
next: middleware::Next,
) -> Result<Response, Infallible> {
println!("layer_two - before handler");
let response = next.run(req).await;
println!("layer_two - after handler");
Ok(response)
}
async fn layer_three(
req: axum::extract::Request,
next: middleware::Next,
) -> Result<Response, Infallible> {
println!("layer_three - before handler");
let response = next.run(req).await;
println!("layer_three - after handler");
Ok(response)
}
async fn handler() -> &'static str {
println!("handler executed");
"Hello, world!"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(handler))
.layer(
ServiceBuilder::new()
.layer(middleware::from_fn(layer_one))
.layer(middleware::from_fn(layer_two))
.layer(middleware::from_fn(layer_three)),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The only change is how the layers are attached. The console now shows this order, also observed live.
layer_one - before handler
layer_two - before handler
layer_three - before handler
handler executed
layer_three - after handler
layer_two - after handler
layer_one - after handler
The first layer listed, layer_one, runs first on the way in and last on the way out. The order reads top to bottom, which is why many developers prefer ServiceBuilder for a stack of several layers. You read the builder from the top and you know the execution order without reversing anything in your head.
The two forms read in opposite directions:
Repeated .layer() calls run bottom to top, last call outermost. A ServiceBuilder runs top to bottom, first listed outermost. The code looks similar in both forms, which is exactly why the order catches people out. When a stack behaves backwards from what you expected, check which form you used before changing anything else.
Mixing layer Calls With a ServiceBuilder
You can combine the two forms. A ServiceBuilder produces a single combined layer, and that combined layer behaves like any other single layer when you apply it with .layer(). The trick is to resolve the inside of the builder first, then apply the repeated .layer() rule to the pieces.
use axum::{
middleware,
response::Response,
routing::get,
Router,
};
use std::convert::Infallible;
use tower::ServiceBuilder;
async fn layer_a(
req: axum::extract::Request,
next: middleware::Next,
) -> Result<Response, Infallible> {
println!("layer_a - before handler");
let response = next.run(req).await;
println!("layer_a - after handler");
Ok(response)
}
async fn layer_b(
req: axum::extract::Request,
next: middleware::Next,
) -> Result<Response, Infallible> {
println!("layer_b - before handler");
let response = next.run(req).await;
println!("layer_b - after handler");
Ok(response)
}
async fn layer_c(
req: axum::extract::Request,
next: middleware::Next,
) -> Result<Response, Infallible> {
println!("layer_c - before handler");
let response = next.run(req).await;
println!("layer_c - after handler");
Ok(response)
}
async fn handler() -> &'static str {
println!("handler executed");
"Hello, world!"
}
#[tokio::main]
async fn main() {
let combined = ServiceBuilder::new()
.layer(middleware::from_fn(layer_b))
.layer(middleware::from_fn(layer_c));
let app = Router::new()
.route("/", get(handler))
.layer(middleware::from_fn(layer_a))
.layer(combined);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Inside the builder, layer_b is listed first, so it is outer and layer_c is inner. The router first gets .layer(layer_a), which wraps only the handler. Then .layer(combined) wraps layer_a and the handler together. The full request path is layer_b, then layer_c, then layer_a, then the handler. The console shows the observed order.
layer_b - before handler
layer_c - before handler
layer_a - before handler
handler executed
layer_a - after handler
layer_c - after handler
layer_b - after handler
The working method is two steps. First, resolve each ServiceBuilder on its own, top to bottom. Then treat each builder as one piece and apply the repeated .layer() rule, last piece outermost, to all the pieces. Mixing the forms is legal, but it is the hardest stack to read. For most applications, put everything in one ServiceBuilder or use only repeated .layer() calls, and do not mix them unless there is a good reason.
TraceLayer and CompressionLayer
The examples from here on use tower-http layers, so they need the tower crate and the matching tower-http features. The dependency block below covers every tower-http example on this page, trace for logging, compression-gzip for compression, limit for the body limit, cors for cross-origin handling, and sensitive-headers for the header marking. The timeout example also needs the timeout feature on tower, and the sensitive-headers example needs tracing and tracing-subscriber for the log setup. There is no bare compression feature, only one feature per format, so gzip is the one used here.
[package]
name = "layer-ordering-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower = { version = "0.5", features = ["timeout"] }
tower-http = { version = "0.7", features = ["trace", "compression-gzip", "limit", "cors", "sensitive-headers"] }
tracing = "0.1"
tracing-subscriber = "0.3"
TraceLayer logs incoming requests and outgoing responses. It is most useful outermost, where it can see the original request before any other middleware changes it, and the final response after all other middleware have processed it. CompressionLayer compresses response bodies, and it only needs to work on the response the handler produced, so it sits well inside TraceLayer, close to the handler.
use axum::{routing::get, Router};
use tower::ServiceBuilder;
use tower_http::{compression::CompressionLayer, trace::TraceLayer};
async fn handler() -> &'static str {
"This response will be compressed if the client accepts gzip."
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(handler))
.layer(
ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
.layer(CompressionLayer::new()),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
In this builder, TraceLayer is listed first, so it is outer. CompressionLayer is listed second, so it is inner. A request flows through TraceLayer, which logs it, then through CompressionLayer, which does nothing on the request side, then to the handler. The response flows back through CompressionLayer, which compresses it when the client accepts it, then through TraceLayer, which logs the response as the handler produced it.
That last point is worth stating precisely. TraceLayer never logs a body size, and it never reads response bodies at all. Its response log carries the status, the latency, and optionally the headers. So keeping compression inside the trace is not about preserving a size number in the log. It is about the trace seeing the handler's response before compression changes it, which is the more useful thing to debug. There is also no risk of double compression from this order. TraceLayer cannot compress anything, because it never touches the body, so nothing is compressed twice.
If you reverse the order and put CompressionLayer outside TraceLayer, the trace sees the already-compressed response instead of the one your handler produced, which is less useful for debugging. The server still works, and nothing breaks loudly. The logs just show you the compressed form.
TimeoutLayer and TraceLayer
A timeout layer puts a maximum duration on a request. If the handler, or any inner middleware, takes too long, the timeout produces an error. That error is not an HTTP response on its own, and a bare timeout layer cannot simply be dropped onto a router and expected to answer with a 408. Two things go wrong if you try.
First, the timeout layer lives behind a feature flag. Tower's timeout support only exists when the timeout feature of the tower crate is enabled, and tower 0.5 has no default features, so a plain tower = "0.5" dependency does not provide it at all. Enable it in Cargo.toml with tower = { version = "0.5", features = ["timeout"] }.
Second, even with the feature on, a bare TimeoutLayer does not satisfy Axum's requirement that middleware on a router be infallible. Its error type is BoxError, and Axum cannot convert that into a response automatically, so the router rejects it at compile time. The official pattern pairs the timeout with HandleErrorLayer from axum::error_handling, which converts the error into a response of your choosing. That layer lives in Axum itself. There is no HandleErrorLayer in tower-http, and tower-http has no error module at all.
use axum::{
error_handling::HandleErrorLayer, http::StatusCode, routing::get, Router,
};
use std::time::Duration;
use tower::ServiceBuilder;
use tower_http::trace::TraceLayer;
async fn slow_handler() -> &'static str {
tokio::time::sleep(Duration::from_secs(10)).await;
"This will never be returned because the timeout fires first."
}
async fn handle_timeout_error(err: axum::BoxError) -> (StatusCode, String) {
if err.is::<tower::timeout::error::Elapsed>() {
(
StatusCode::REQUEST_TIMEOUT,
"request timed out".to_string(),
)
} else {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("something went wrong: {err}"),
)
}
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(slow_handler))
.layer(
ServiceBuilder::new()
.layer(HandleErrorLayer::new(handle_timeout_error))
.timeout(Duration::from_secs(2))
.layer(TraceLayer::new_for_http()),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The handler sleeps for 10 seconds. The timeout is 2 seconds. ServiceBuilder::timeout adds tower's TimeoutLayer, and the HandleErrorLayer above it catches the timeout error and turns it into a 408. A live run of this program confirmed it, a request to this router returned 408 Request Timeout in about 2 seconds, while the handler would have taken 10. The timeout produces an Elapsed error, not a 408, and the 408 only exists because the error handler maps it to one. Without the error handler, there is no 408 at all.
Where should the timeout sit relative to TraceLayer? A sensible choice is outside it. The timeout then bounds everything inside, including the tracing layer itself, and the trace still sees the request and can log that it timed out. Here the HandleErrorLayer is outermost of the three, then the timeout, then TraceLayer closest to the handler. If the timeout were inside TraceLayer, the trace would still see the resulting error response, but the timeout would not bound any time spent in the tracing layer itself. When a layer might block, the timeout belongs outside it.
Note also that a timeout only times the inner service's call, after the request head is received. It does not protect against a client that connects and sends nothing, because there is no request for the timeout to time yet.
SetSensitiveHeadersLayer and TraceLayer
SetSensitiveHeadersLayer marks certain headers as sensitive so that TraceLayer redacts their values in logs. The layer lives in tower_http::sensitive_headers. It does not live in tower_http::set_header, which holds only the layers that set header values, so that import path does not compile.
For the redaction to work, the marking must happen before TraceLayer logs the headers. That means the sensitive layer must sit outside TraceLayer. In a ServiceBuilder, the first layer listed is outermost, so the sensitive layer is listed first.
use axum::{http::header::HeaderName, routing::get, Router};
use tower::ServiceBuilder;
use tower_http::{
sensitive_headers::SetSensitiveHeadersLayer,
trace::TraceLayer,
};
async fn handler() -> &'static str {
"Hello"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(handler))
.layer(
ServiceBuilder::new()
.layer(SetSensitiveHeadersLayer::new(std::iter::once(
HeaderName::from_static("x-api-key"),
)))
.layer(TraceLayer::new_for_http()),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The mechanism is simple, and it is not an extension. The layer calls set_sensitive(true) on the HeaderValue of each matching header, on the request on the way in and on the response on the way out. TraceLayer checks that flag when it logs and prints Sensitive in place of the value.
The opposite order leaks. If TraceLayer is listed first in the builder, it logs the request before the marking happens, and the live value appears in the log. Both orders were run live while writing this page, with header logging enabled and a custom x-api-key header. The sensitive-outside run printed this line.
INFO request{method=GET uri=/ version=HTTP/1.1 headers={"x-api-key": Sensitive}}: tower_http::trace::on_request: started processing request
The sensitive-inside run printed this line for the same request.
INFO request{method=GET uri=/ version=HTTP/1.1 headers={"x-api-key": "my-secret-key"}}: tower_http::trace::on_request: started processing request
The secret is printed in full. The only difference between the runs was the order of the two layers in the builder. One more detail decides whether either line appears at all. TraceLayer logs no headers by default, so header logging must be turned on with .include_headers(true) on the span builder and on the response handler, and both sides must log at info level, or the lines stay hidden. The example above leaves those settings out for brevity. The complete version, with them in place, looks like this.
use axum::{routing::get, Router};
use tower::ServiceBuilder;
use tower_http::{
sensitive_headers::SetSensitiveHeadersLayer,
trace::{DefaultMakeSpan, DefaultOnRequest, DefaultOnResponse, TraceLayer},
};
use tracing::Level;
async fn handler() -> &'static str {
"Hello"
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_max_level(Level::INFO)
.init();
let app = Router::new()
.route("/", get(handler))
.layer(
ServiceBuilder::new()
.layer(SetSensitiveHeadersLayer::new(std::iter::once(
axum::http::header::HeaderName::from_static("x-api-key"),
)))
.layer(
TraceLayer::new_for_http()
.make_span_with(
DefaultMakeSpan::new()
.level(Level::INFO)
.include_headers(true),
)
.on_request(DefaultOnRequest::new().level(Level::INFO))
.on_response(
DefaultOnResponse::new()
.level(Level::INFO)
.include_headers(true),
),
),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Send a request with -H "x-api-key: my-secret-key" and the log shows the first line above, with Sensitive in place of the key. Swap the two layers in the builder and the same request shows the second line, with the live key printed in full.
Sensitive inside the logger leaks the secret:
To redact a header in TraceLayer, the sensitive layer must sit outside the logger. In a ServiceBuilder, list it before TraceLayer. With repeated .layer() calls, add it after TraceLayer, because the last call is outermost. Reversing the order compiles and runs, and the secret lands in the log file.
CorsLayer and TraceLayer
CorsLayer handles cross-origin resource sharing. It answers preflight requests, which are the small OPTIONS requests a browser sends before the real request, and it adds the headers that tell the browser the cross-origin call is allowed. It should sit early in the stack, because it needs to intercept those preflight requests before they reach the handler. The bare CorsLayer::new() in the example below allows no origins, methods, or headers at all until it is configured, so a real application must add calls such as .allow_origin(Any) and .allow_methods(Any) to actually permit cross-origin requests. The ordering point below stands either way, and the configuration itself belongs to the layer's own setup.
TraceLayer is also a candidate for the outermost spot, because you want it to log everything, including preflight requests. Putting TraceLayer outermost and CorsLayer inside it logs the preflight, then passes it to CorsLayer, which may answer directly without the handler running. That is fine, and it is the usual arrangement.
use axum::{routing::get, Router};
use tower::ServiceBuilder;
use tower_http::{cors::CorsLayer, trace::TraceLayer};
async fn handler() -> &'static str {
"Hello, world!"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(handler))
.layer(
ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
.layer(CorsLayer::new()),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The tradeoff is visible if you flip the order. With CorsLayer outermost, a preflight that CorsLayer answers directly never reaches TraceLayer, so the preflight is never logged. With TraceLayer outermost, every preflight is logged, and the CORS layer still does its job inside. Choose by asking whether the preflight requests belong in your logs. Most of the time, they do, because a missing preflight log makes CORS problems harder to debug.
RequestBodyLimitLayer and TraceLayer
RequestBodyLimitLayer caps the size of the request body. If the body is larger than the limit, it answers with a 413 and the handler never runs. It must sit outside any layer that reads the request body, or that layer could read the whole body before the limit is checked. TraceLayer does not read the body, so it can sit on either side of the limit. The usual arrangement puts the trace outermost for logging, and the limit just inside it, before anything that reads the body.
use axum::{routing::get, Router};
use tower::ServiceBuilder;
use tower_http::{limit::RequestBodyLimitLayer, trace::TraceLayer};
async fn handler() -> &'static str {
"Hello, world!"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(handler))
.layer(
ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
.layer(RequestBodyLimitLayer::new(1024 * 1024)),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The limit here is 1 megabyte. Any layer that reads the body would be listed after the limit, closer to the handler, so the limit guards it. If the limit were listed after a body-reading layer, the reader would consume the body first and the limit would be useless. The rule is the same as for the timeout. A guard belongs outside the thing it guards.
A Decision Framework for Placing Layers
When you add a layer to a stack, ask three questions in order. They settle most placements without memorising a table.
First, what does this layer need to see. A logger needs the original request and the final response. A body limit needs the body before anyone reads it. A sensitive-header layer needs the headers before anyone logs them. A timeout needs everything it bounds to be inside it.
Second, what does this layer change. A layer that changes the response, like compression, should sit close to the handler, so the outer layers see the response as the handler produced it. A layer that changes the request, like one that adds a header, should sit where the layers that need that header can see the change.
Third, what happens when this layer short-circuits. A layer that answers early, like CORS on a preflight or an auth layer on a missing token, stops the request from reaching the layers inside it. Anything that must see every request, such as logging, belongs outside a layer that can short-circuit.
Work through those three questions for each layer, then write the stack in one form, a ServiceBuilder read top to bottom, or repeated .layer() calls read bottom to top, and do not mix the two without a reason.
Common Mistakes
Mixing up the two ordering rules
Repeated .layer() calls run bottom to top. A ServiceBuilder runs top to bottom. Writing a stack in one form while thinking in the other reverses the whole stack. Pick one form per stack and read it in that form's direction.
Placing the sensitive layer inside the logger
This is the mistake with the worst consequences, because it is silent. The server runs, the logs look normal, and the secret is in them. The sensitive layer belongs outside TraceLayer, always.
Dropping a bare TimeoutLayer onto a router
A bare TimeoutLayer does not compile on Router::layer, because its error type cannot be converted into a response. It also does not exist without the timeout feature on tower. Pair it with HandleErrorLayer from axum::error_handling, and remember that the timeout produces an Elapsed error, not a 408. The 408 comes from your error handler.
Importing SetSensitiveHeadersLayer from set_header
The set_header module holds only SetRequestHeaderLayer and SetResponseHeaderLayer. The sensitive layer lives in sensitive_headers. The wrong path fails to compile with a "module does not contain that type" error.
Expecting TraceLayer to log body sizes
TraceLayer never logs a body size and never reads a response body. If you place compression outside the trace because you want the trace to record the uncompressed size, you are solving a problem that does not exist. Keep compression inside the trace because the trace should see the handler's response, not because of any size number.
Assuming order does not matter for independent layers
Layers that look independent often interact through headers, extensions, or early returns. A propagator and a logger interact through the response headers. A limit and a body reader interact through the body. Think about what flows between two layers before deciding their order does not matter.
One form per stack:
A stack written entirely as repeated .layer() calls, or entirely as one ServiceBuilder, is easy to read and easy to check. A stack that mixes the two is legal, but every reader has to resolve the builder first and then reverse the outer calls. Save the mixed form for the day a stack genuinely needs it.
Testing Your Order With a Small Logger
If you are unsure about a stack, test it with a temporary middleware that prints when it runs. Write the closures inline with from_fn, rather than naming the layer type by hand. The return type of from_fn takes four generic parameters, and writing it by hand is easy to get wrong. Inline closures keep the test small and let the compiler infer the types.
use axum::{
middleware,
response::Response,
routing::get,
Router,
};
use std::convert::Infallible;
use tower::ServiceBuilder;
async fn handler() -> &'static str {
"Hello"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(handler))
.layer(
ServiceBuilder::new()
.layer(middleware::from_fn(
|req: axum::extract::Request, next: middleware::Next| async move {
println!("outer - start");
let response = next.run(req).await;
println!("outer - end");
Ok::<Response, Infallible>(response)
},
))
.layer(middleware::from_fn(
|req: axum::extract::Request, next: middleware::Next| async move {
println!("inner - start");
let response = next.run(req).await;
println!("inner - end");
Ok::<Response, Infallible>(response)
},
)),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Send one request and read the console. The output confirms the order directly: outer - start, inner - start, the handler, inner - end, outer - end. The first layer in the builder is the outer one, and the second is the inner one. Replace the two closures with the real layers you are unsure about, keep the prints, and the output tells you the truth about your stack in one request. Delete the test middleware when you are done.
Summary
Layer ordering is not a matter of taste. It decides what each layer can see, and the failures from getting it wrong are silent. Two rules cover the mechanics. With repeated .layer() calls, the last call is outermost and runs first. With a ServiceBuilder, the first layer listed is outermost and runs first. The pairs follow from asking what each layer needs to see. Logging goes outermost so it sees everything. A sensitive-header layer goes outside the logger so the marking happens before the logging. Compression goes inside the logger so the trace sees the handler's response. A timeout goes outside everything it must bound, with an error handler that turns its error into the status you want. A body limit goes outside anything that reads the body. When in doubt, write the stack in one form, print the order with a temporary logger, and trust the output over your memory of the rule. The output is one request away, and it never lies about the order.