Cross-cutting concerns in Axum middleware
Learn what cross-cutting concerns are, why they belong in middleware instead of handlers, and how to apply them in Axum with working examples
When you build a web application, you often need certain behaviors to apply to many different endpoints. Logging every request, measuring how long each request takes, checking whether a user is logged in before allowing access, compressing responses to save bandwidth, adding a request ID to every response. These are all examples of cross-cutting concerns. They are called cross-cutting because they cut across the boundaries of your individual route handlers. Instead of writing the same logging code inside every handler, you write it once and attach it to the whole application or a group of routes. Axum gives you a clean way to do this through middleware.
This page explains what cross-cutting concerns are, why they matter, and how to handle them in Axum with the tower middleware system. You will see a working logging example, learn the three scopes where middleware can be attached, learn the trap that catches almost everyone who tries to scope middleware to one route, and build a small stack of several layers working together.
What cross-cutting concerns are
A cross-cutting concern is a piece of functionality that is needed in many different parts of a program. In a web server, these concerns typically involve processing the incoming HTTP request, the outgoing response, or both. The common ones are easy to recognize once you know the name.
Logging records the method, path, status code, and duration for every request. Authentication verifies that the request comes from a logged-in user. Authorization checks whether that user has permission to access the endpoint. Compression shrinks response bodies to reduce network traffic. Common headers add values like x-request-id, cache-control, or security headers to responses. Rate limiting restricts how many requests a client can make in a time period. Timeout enforcement stops a handler from running indefinitely. Tracing emits structured events so you can follow a request through a whole system.
What makes these concerns cross-cutting is that none of them belongs to one handler. Logging belongs to all of them. Authentication belongs to all of them except the public ones. Compression belongs to every response that is large enough to benefit. The concern is horizontal. It stretches across the application, while each handler is vertical, focused on one small job. Middleware exists to handle the horizontal concerns in one place, so the vertical handlers stay focused.
The problem middleware solves
Imagine an Axum application with five handlers. One serves the home page, one lists products, one creates a product, one shows a user profile, and one deletes a user. Each handler needs to log the incoming request, check whether the user is authenticated, measure how long the handler takes, and add a request ID header to the response.
You could write a helper function and call it at the beginning and end of each handler. That still requires every handler to remember to call it, and it clutters the handler code with logic that has nothing to do with the handler's real job. Worse, if you forget to call it in one handler, that endpoint behaves differently from the rest, and the difference is silent. Nobody will notice until a request to that endpoint goes missing from the logs, or an unauthenticated user reaches a handler that was supposed to be protected.
Middleware offers a better approach. You wrap all five handlers with layers that do the logging, authentication, timing, and header injection automatically. The handlers stay focused on their actual business logic. The middleware runs before and after each handler without the handler needing to know it exists. When you change the logging format, you change it in one place. When you add a sixth handler, it gets the same behavior for free, because the middleware wraps the router, not the handler.
Think of it like airport security. Every passenger goes through the same check, no matter which flight they are catching. The check does not belong inside each gate. It sits at one point that every passenger passes through. Middleware is that checkpoint. Handlers are the gates.
How Axum handles cross-cutting concerns
Axum is built on top of the tower ecosystem. Tower is a library for writing modular and reusable components called services and layers. A service is something that receives a request and returns a response. Your Axum handlers, combined with routing, form a service. A layer is a way to wrap one service with additional behavior, producing a new service. That is exactly what middleware is, a layer that adds cross-cutting behavior to your endpoints.
Axum's Router itself implements the Service trait. When you call .layer(...) on a Router, you are wrapping the entire router, all the routes inside it, with that layer. The layer becomes part of the service chain. When a request arrives, it first goes through the outermost layer, then through inner layers, until it finally reaches the handler. The response travels back through the layers in reverse order.
This nesting is often compared to an onion. Each layer is a skin around the core handler. The request peels through the layers inward, and the response comes back outward. Any layer can also stop the chain early. An authentication layer can return a 401 Unauthorized response immediately without ever calling the handler, for example. That early return is called short-circuiting, and you will see it in action later on this page.
The onion model of middleware
Understanding the onion model is essential, because it explains the order in which middleware executes. Consider three layers applied to a router, named layer_one, layer_two, and layer_three, added in that order.
requests
|
v
+----- layer_three -----+
| +---- layer_two ----+ |
| | +-- layer_one --+ | |
| | | | | |
| | | handler | | |
| | | | | |
| | +-- layer_one --+ | |
| +---- layer_two ----+ |
+----- layer_three -----+
|
v
responses
When a request comes in, layer_three receives it first. It can inspect or modify the request, then decide whether to pass it inward. If it passes inward, layer_two receives the request next. Then layer_one. Then the handler. The handler produces a response. That response goes back through layer_one, which can modify it, then through layer_two, then through layer_three, which returns the final response to the client.
The last layer you add is the first to see the request. That is the single most surprising fact about repeated .layer() calls, and it is worth memorizing now. The reason is that each new layer wraps everything that came before it. The first layer added sits closest to the handler. The last layer added sits closest to the outside world.
Step 1: The outermost layer receives the request
The request arrives at the server. Axum passes it to the outermost middleware layer, which is the one you applied last. That layer gets the first chance to inspect or modify the request.
Step 2: Middleware passes the request inward
The outermost layer, after doing its pre-processing, calls the next inner layer. That layer does its own pre-processing and calls the next one, and so on, until the request reaches the actual handler.
Step 3: The handler produces a response
The handler runs its business logic and returns a response. At this point, the request has gone as deep as it can go.
Step 4: The response travels back outward
The response now moves back through each layer in reverse order. Each layer can inspect or modify the response before passing it further out. The outermost layer finally sends the response to the client.
This model is essential when you have layers that depend on each other. A tracing layer that wants to log the duration of the entire request must sit outside the other layers, so its start timer runs before the inner layers and its stop timer runs after the handler returns. If it sits inside, it measures only part of the journey. Order is not decoration. It decides what each layer can see.
A first working example, logging every request
Start with a simple application that has two routes, and add a ready-made logging layer to both of them. The layer is TraceLayer from the tower-http crate. It integrates with the tracing crate to emit structured logs for each request. You do not need to write any logging code yourself. You attach the layer, and the logging happens.
Add the required dependencies to Cargo.toml. These are the current versions, axum 0.8.9 with tower-http 0.7.1.
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tower-http = { version = "=0.7.1", features = ["trace"] }
tracing = "0.1"
tracing-subscriber = "0.3"
Now build the application and apply the TraceLayer to the whole router.
use axum::{routing::get, Router};
use tower_http::trace::TraceLayer;
async fn hello() -> &'static str {
"Hello, world!"
}
async fn goodbye() -> &'static str {
"Goodbye!"
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();
let app = Router::new()
.route("/hello", get(hello))
.route("/goodbye", get(goodbye))
.layer(TraceLayer::new_for_http());
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Run it and request http://127.0.0.1:3000/hello. The terminal shows lines like these.
DEBUG request{method=GET uri=/hello version=HTTP/1.1}: tower_http::trace::on_request: started processing request
DEBUG request{method=GET uri=/hello version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=1 ms status=200
The first line appears when the request arrives. The second appears when the response is ready, and it carries the latency and the status code. Both lines are wrapped in a span called request, which groups all the events for one request together. The span field is uri=, not path=. That naming matters if you ever filter or search your logs by field name. A third line can also appear after the response, on_eos: end of stream, which fires once the response body has finished streaming to the client.
This demonstrates the core idea. A cross-cutting concern, logging, was added once and now applies to multiple endpoints without touching their code. The handlers still return their plain strings. The layer does all the logging work around them.
TraceLayer logs at DEBUG level, and the default subscriber hides DEBUG:
With plain tracing_subscriber::fmt().init(), you will see no log output at all from this example. TraceLayer emits its request span and its started and finished events at DEBUG level, while the default subscriber only shows events at INFO level and above, so every TraceLayer event is filtered out before it is printed. The fix is the .with_max_level(tracing::Level::DEBUG) call in the example above. If your logs are silent, check the level first. It is the most common reason a working TraceLayer appears to do nothing.
Applying middleware at different scopes
Not every concern should apply to every route. Authentication might be required only for admin endpoints, while public endpoints stay open. Axum lets you scope middleware to the whole router, to a set of routes, or to a single handler. Which one you choose decides which endpoints the concern affects, and the wrong choice is a real bug, not a style preference.
Global middleware with Router::layer
Router::layer wraps all routes that were added before the .layer() call. If you add routes after calling .layer(), they will not be wrapped. The order of .route() and .layer() calls matters, and this catches beginners out.
Here is an example that shows the effect of order.
use axum::{routing::get, Router};
use tower_http::trace::TraceLayer;
async fn public() -> &'static str {
"Public"
}
async fn admin() -> &'static str {
"Admin"
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();
let app = Router::new()
.route("/public", get(public))
.layer(TraceLayer::new_for_http())
.route("/admin", get(admin));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
In this code, the TraceLayer only logs requests to /public. The /admin route was added after the layer, so it does not go through that middleware. That behavior surprises people who assume .layer() applies to the entire router regardless of order. To apply the layer to all routes, place the .layer() call after all your routes have been defined.
let app: Router = Router::new()
.route("/public", get(public))
.route("/admin", get(admin))
.layer(TraceLayer::new_for_http());
This is the typical pattern for global middleware. Routes first, layer last. When you add a new route later, add it before the .layer() call, or it will silently escape the middleware.
Route middleware with Router::route_layer, and the trap
If you want middleware to apply only to certain routes, the tempting call is route_layer. The name suggests it scopes a layer to a route. It does not scope to one route. route_layer wraps every route added to the router so far, and the layer runs only when a request actually matches one of those routes. That second half, it runs only on a match, is the real difference from Router::layer, which runs even for unmatched requests. The first half, every route added so far, is the trap.
Here is the trap as a working example. The middleware checks for an x-auth-token header and returns 401 Unauthorized when the header is missing. The intent is to protect only /admin. The code below uses route_layer, and the result is not what the author intended.
use axum::{
extract::Request,
http::StatusCode,
middleware::{self, Next},
response::Response,
routing::get,
Router,
};
async fn public() -> &'static str {
"Public"
}
async fn admin() -> &'static str {
"Admin panel"
}
async fn require_auth(request: Request, next: Next) -> Result<Response, StatusCode> {
if request.headers().contains_key("x-auth-token") {
Ok(next.run(request).await)
} else {
Err(StatusCode::UNAUTHORIZED)
}
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/public", get(public))
.route("/admin", get(admin))
.route_layer(middleware::from_fn(require_auth));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The require_auth function is written with middleware::from_fn, which turns an ordinary async function into middleware. It looks at the request headers, and if the x-auth-token header is present, it calls next.run(request) to pass the request on to the handler. If the header is missing, it returns Err(StatusCode::UNAUTHORIZED), and from_fn converts that into a 401 response. The middleware itself is correct. The scoping is wrong.
Tested at runtime, GET /public without the token returns 401, exactly like /admin. Both routes got the layer, because route_layer wraps every route added before the call, and both routes were added before it. There is no per-call scoping window and no rule about the most recently added route. If your public page starts returning 401 after you add an auth layer, this is the first thing to check.
route_layer does not scope to one route:
route_layer wraps every route currently in the router. If you call it after adding /public and /admin, both routes get the layer. There is no way to use route_layer to protect only /admin. For one route only, attach the middleware to that route with MethodRouter::layer, as shown in the next section. This mistake locks real users out of public pages, and the code looks correct at a glance, which is what makes it dangerous.
To protect only /admin, attach the middleware to that route alone with MethodRouter::layer. The call get(admin).layer(...) wraps just that method router, so /public stays open.
let app: Router = Router::new()
.route("/public", get(public))
.route(
"/admin",
get(admin).layer(middleware::from_fn(require_auth)),
)
.layer(TraceLayer::new_for_http());
Tested at runtime, GET /public without a token now returns 200, and GET /admin without a token returns 401. The TraceLayer is added after everything, so it wraps both routes and logs both. The order of execution for /admin is TraceLayer on the outside, then require_auth, then the handler. For /public, only TraceLayer runs. That is the shape you want. Global concerns on the router, scoped concerns on the route.
Handler middleware with Handler::layer
Sometimes you want middleware for a single handler only, not an entire route. A route can have several handlers for different HTTP methods, and Handler::layer attaches middleware to one specific handler function before it is passed to get(...).
use axum::{
extract::Request,
handler::Handler,
http::StatusCode,
middleware::{self, Next},
response::Response,
routing::get,
Router,
};
async fn index() -> &'static str {
"Index"
}
async fn secret() -> &'static str {
"Secret"
}
async fn require_auth(request: Request, next: Next) -> Result<Response, StatusCode> {
if request.headers().contains_key("x-auth-token") {
Ok(next.run(request).await)
} else {
Err(StatusCode::UNAUTHORIZED)
}
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(index))
.route("/secret", get(secret.layer(middleware::from_fn(require_auth))));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Here, only the GET /secret handler is protected. GET / stays open, even though both routes live in the same router. This form is useful when the same path serves different handlers for different methods and only one of them needs the check. The handler::Handler import is required, because the .layer method on a handler function comes from the Handler trait, and Rust only finds trait methods that are in scope.
Three scopes, three different coverages:
Router-level middleware with Router::layer covers every route added before the call. Router::route_layer also covers every route added before the call, but it only runs when a request matches a route. MethodRouter::layer and Handler::layer cover one route or one handler. When a concern applies to the whole application, use the router. When it applies to one endpoint, use the route or the handler. The middle option, route_layer, is for the case where you want the layer to run only on matched routes, not for scoping to a single route.
Composing several layers with ServiceBuilder
Real applications often need several cross-cutting concerns at once. Axum allows you to stack layers with repeated .layer() calls, but the recommended way is to use tower::ServiceBuilder. ServiceBuilder composes layers in a clear top-to-bottom order and avoids the confusion of repeated .layer() calls, where the last call added is the outermost.
Add the dependencies. The timeout and compression-full features enable the timeout and compression layers, and trace enables the tracing layer.
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tower = "=0.5.3"
tower-http = { version = "=0.7.1", features = ["trace", "compression-full", "timeout"] }
tracing = "0.1"
tracing-subscriber = "0.3"
Here is a stack of three layers, logging, compression, and a timeout, applied to a slow handler.
use axum::{http::StatusCode, routing::get, Router};
use std::time::Duration;
use tower::ServiceBuilder;
use tower_http::{
compression::CompressionLayer,
timeout::TimeoutLayer,
trace::TraceLayer,
};
async fn slow_handler() -> &'static str {
tokio::time::sleep(Duration::from_secs(2)).await;
"This took 2 seconds"
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();
let middleware_stack = ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
.layer(CompressionLayer::new())
.layer(TimeoutLayer::with_status_code(
StatusCode::REQUEST_TIMEOUT,
Duration::from_secs(1),
));
let app = Router::new()
.route("/slow", get(slow_handler))
.layer(middleware_stack);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Request this endpoint and the handler takes 2 seconds, but the timeout is 1 second, so the client receives a 408 Request Timeout after about 1 second instead of waiting for the handler. The TimeoutLayer::with_status_code constructor is the current form. The older TimeoutLayer::new constructor is deprecated since tower-http 0.6.7, and the new form returns a 408 response directly, so no extra error handling layer is needed around it.
In this stack, ServiceBuilder runs its layers top to bottom. The first layer listed is the outermost. TraceLayer is outermost, so it starts timing before the request goes inward and logs after the response comes back out. CompressionLayer sits in the middle and compresses response bodies when the client supports it. TimeoutLayer is innermost, closest to the handler, and enforces that the handler completes within 1 second.
Ordering with repeated .layer() calls is reversed:
If you instead call .layer() multiple times directly on the router, the last .layer() you add becomes the outermost layer. That is the opposite of ServiceBuilder, where the first layer listed is outermost. Mixing the two styles in one application is a reliable source of ordering bugs. When you stack more than two layers, use ServiceBuilder and read the order top to bottom.
The execution order of a stack
Walk through the request to /slow step by step, because the order decides what each layer can observe. The request enters TraceLayer first. TraceLayer opens its span and passes the request to CompressionLayer. CompressionLayer passes it to TimeoutLayer. TimeoutLayer starts its timer and calls the handler. The handler sleeps for 2 seconds. After 1 second, the timeout fires and produces a 408 response without waiting for the handler. That response travels outward through CompressionLayer, which may compress it, and then through TraceLayer, which logs the status and the latency and closes the span.
Request -> TraceLayer -> CompressionLayer -> TimeoutLayer -> handler
Response <- TraceLayer <- CompressionLayer <- TimeoutLayer <- handler
Tested at runtime, the client receives status 408 after about 1.002 seconds, and the trace log shows latency=1001 ms status=408. The trace layer measured the whole stack, including the time the timeout spent waiting, because it sits outside the timeout. If the timeout had sat outside the trace layer, the trace log would never appear for timed-out requests, because the trace layer would never run. Position decides visibility.
One ordering idea needs correcting, because it sounds plausible and is wrong. You might think the timeout should sit outside the compression layer so that it covers the time compression takes. That reasoning fails for two reasons. Compression streams the response body chunk by chunk, it does not wait for the whole body before compressing, so there is no single compression step for the timeout to cover. And tower-http's timeout only times the inner service's response future, not the streaming of the body, so placing the timeout inside or outside the compression layer does not change what the timeout measures in the way you might expect. What the ordering does decide is which layer sees the request first and the response last. Here TraceLayer times the whole stack, and the timeout applies to the handler's response while compression still applies to the body on the way out. Choose the order by what each layer needs to see, not by an imagined coverage of the others.
Choosing the right ready-made layer
Axum and the tower ecosystem provide many pre-built layers for common concerns. Before writing custom middleware, check whether tower-http or another crate already offers what you need. Using a pre-built layer is faster and less error-prone than writing your own, and the layers below are all applied with the same .layer() or ServiceBuilder mechanisms you have learned on this page.
| Concern | Ready-made layer |
|---|---|
| Logging and tracing | TraceLayer from tower-http |
| CORS, letting browsers call your API from other origins | CorsLayer from tower-http |
| Compression | CompressionLayer from tower-http |
| Request IDs, setting and propagating them | SetRequestIdLayer and PropagateRequestIdLayer from tower-http |
| Timeout | TimeoutLayer from tower-http, using with_status_code |
| Request body size limits | RequestBodyLimitLayer from tower-http |
| Serving static files | ServeDir from tower-http |
| Adding headers to requests or responses | SetRequestHeaderLayer and SetResponseHeaderLayer from tower-http |
| Marking headers as sensitive so logs redact them | SetSensitiveHeadersLayer from tower-http |
Rate limiting deserves a caution rather than a row in this table. The general rate-limit layer from tower does not behave as expected inside Axum, so do not pick it from a list and assume it works. Rate limiting is a real concern, and it needs a solution built for how Axum applies layers. For this page, the takeaway is that the list above covers the concerns with reliable ready-made layers, and anything outside it deserves a closer look before you trust it.
When to write custom middleware
Sometimes no existing layer fits your exact need. You may need to check a custom session token, change a response based on request data, or perform some application-specific logic that no generic layer could know about. In those cases, you write your own middleware. Axum offers several ways, from writing a plain async function with middleware::from_fn to implementing the tower::Service trait directly. Those techniques are the subject of their own coverage, and they all produce a layer that wraps your router, so they work exactly the same way from the router's perspective. The rule for choosing is simple. If a ready-made layer exists, use it. If the logic is specific to your application, write it with from_fn. If the logic must be reusable across projects or published as a crate, implement Service and Layer directly.
Common mistakes when working with cross-cutting middleware
Applying middleware too early in router construction is the first mistake. Because .layer() only affects routes added before it, it is easy to add a route after the layer and wonder why the middleware never runs. Always place global .layer() calls after all route definitions. When you add a new route later, add it before the layer call.
Assuming route_layer scopes to one route is the second, and it is the most damaging. route_layer wraps every route added so far. The public page that starts returning 401 after you add an auth layer is the classic symptom. Use MethodRouter::layer on the single route instead.
Forgetting to initialize tracing is the third. If you use TraceLayer but never set up a tracing subscriber, you will see no logs at all. The layer emits events, but nothing displays them without a subscriber. And even with a subscriber, remember the level. TraceLayer logs at DEBUG, so a default subscriber hides its output.
Expecting middleware to run for unmatched requests is the fourth. A layer applied with route_layer only runs when a request matches a route. If you rely on it to log 404s or to add headers to 404 responses, it will not run, because there is no matched route. Router::layer runs for unmatched requests too, which is why logging usually belongs on the router.
Returning errors instead of responses from custom middleware is the fifth. If a middleware service returns an error that is not handled, the connection closes without sending a response, and the client sees a network failure instead of a status code. Axum requires handlers to always return a response, and the same rule applies to middleware. Convert failures into responses inside the middleware. For middleware written with from_fn, that conversion happens automatically, because from_fn turns an error into a response itself. For fallible tower layers, pair them with axum::error_handling::HandleErrorLayer, which converts the error into a response. Note the path. The error handling layer lives in axum::error_handling, not in tower-http, which has no error module at all.
Unhandled middleware errors close the connection:
If a middleware service returns an error and nothing converts it into a response, the HTTP server underneath Axum closes the connection without sending anything. The client sees a dropped connection rather than a clean HTTP error status. Always convert errors into responses inside your middleware, or pair a fallible tower layer with axum::error_handling::HandleErrorLayer. A 401 or 500 status is a message. A closed connection is silence.
A quick check that your stack is wired correctly:
Request a slow endpoint with a 1 second timeout and confirm you get a 408 after about 1 second, not after the handler finishes. Request a public endpoint and an admin endpoint without a token and confirm the public one returns 200 while the admin one returns 401. If both checks pass, your scopes and your ordering are correct.
Summary
Cross-cutting concerns are the behaviors that stretch across many endpoints, logging, authentication, compression, timeouts, and the rest. Axum handles them through middleware layers, which wrap handlers in an onion-like structure. Requests travel through layers from the outermost to the innermost, and responses travel back in reverse. You can apply middleware globally with Router::layer, to matched routes with route_layer, or to a single route or handler with MethodRouter::layer and Handler::layer. The order of layers matters, and ServiceBuilder is the recommended way to compose several layers because its ordering reads top to bottom.
The decision framework that falls out of this page has three questions. First, which endpoints does the concern affect. If it is all of them, use the router. If it is one, use that route or handler. If you catch yourself reaching for route_layer to protect one route, stop, because it covers every route added so far. Second, what does each layer need to see. Put the layer that must observe the whole request, like tracing, on the outside. Put the layer that guards the handler, like a timeout, on the inside. Third, does a ready-made layer already exist. If it does, use it. The most valuable skill here is thinking about your application in terms of layers, which concerns are global, which are scoped, and in what order they should run. Once you have that mental model, applying the middleware becomes straightforward.