Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 38 ยท State and Middleware

Axum Middleware with tower-http: CORS, Trace, Compression

Use ready-made tower-http layers in Axum: TraceLayer logging, CorsLayer and preflight requests, compression, timeouts, body limits, request ids and static files.

Writing your own middleware with from_fn is great for rules that belong to your application. But the web has a standard set of cross-cutting problems: logging every request, answering CORS preflights, compressing responses, cutting off slow requests, limiting body sizes, tagging requests with ids. Solving those once, well, is the job of tower-http, a collection of production-quality Tower layers maintained alongside Axum.

Each layer is enabled by a Cargo feature, so you only compile what you use:

TOML
tower-http = { version = "0.6", features = ["trace", "cors", "compression-gzip", "timeout", "limit", "request-id", "fs", "catch-panic", "set-header"] }

Check the crate's documentation for the exact version your Axum release pairs with; the layer names below are stable, but a few constructors change between versions.

Tracing every request: TraceLayer

Rust
use tower_http::trace::TraceLayer;

let app = Router::new()
    .route("/", get(home))
    .layer(TraceLayer::new_for_http());

With a tracing subscriber installed (see logging and configuration), each request produces a span with the method, the URI and the version, plus events when the response arrives (status and latency) or when the request fails. Set RUST_LOG=tower_http=debug to see them. You can customise the span (make_span_with) to add a request id or a user id, and tune the events (on_response) to log at a different level.

CORS: CorsLayer

Browsers block JavaScript on one origin (https://app.example.com) from reading responses from another (https://api.example.com) unless the API opts in. The opt-in is a set of access-control-* headers; CorsLayer generates them:

Rust
use axum::http::{header, HeaderValue, Method};
use tower_http::cors::CorsLayer;

let cors = CorsLayer::new()
    .allow_origin("https://app.example.com".parse::<HeaderValue>().unwrap())
    .allow_methods([Method::GET, Method::POST, Method::DELETE])
    .allow_headers([header::CONTENT_TYPE, header::AUTHORIZATION])
    .allow_credentials(true)
    .max_age(std::time::Duration::from_secs(3600));

let app = Router::new().route("/items", get(items)).layer(cors);

How CORS works in two steps:

  1. Simple requests (GET without special headers) are sent directly. The server answers, and the browser decides whether to hand the response to the script based on access-control-allow-origin.
  2. Preflighted requests (JSON POST, Authorization header, PUT, DELETE) are preceded by an OPTIONS request that asks permission. CorsLayer answers that preflight itself, so your handler never sees it.

Rules that trip people up:

  • allow_origin(Any) is fine for a public, credential-free API. You cannot combine Any with allow_credentials(true); the browser refuses and the layer panics at start-up. List the real origins instead.
  • CORS protects browsers, not your server. curl ignores it. It is not authentication.
  • Put CorsLayer outside authentication so preflights (which carry no credentials) are not rejected with 401.

Compression: CompressionLayer

Rust
use tower_http::compression::CompressionLayer;

let app = Router::new().route("/report", get(report)).layer(CompressionLayer::new());

The layer looks at the request's accept-encoding, compresses the body with a supported algorithm (gzip, brotli, deflate or zstd, depending on the enabled features) and sets content-encoding. It skips already compressed content types such as images and very small bodies. Pair it with RequestDecompressionLayer if clients may upload compressed bodies. If a reverse proxy such as nginx or Cloudflare already compresses, do it in one place only.

Timeouts and body limits

Rust
use std::time::Duration;
use tower_http::{limit::RequestBodyLimitLayer, timeout::TimeoutLayer};

let app = Router::new()
    .route("/upload", post(upload))
    .layer(RequestBodyLimitLayer::new(10 * 1024 * 1024))                  // 10 MB
    .layer(TimeoutLayer::new(Duration::from_secs(15)));                    // 408 after 15 s

A request that takes too long is aborted and answered with a timeout status, so a stuck database call cannot pin a connection forever. Newer tower-http releases prefer TimeoutLayer::with_status_code(status, duration), which makes the status explicit. RequestBodyLimitLayer rejects oversized bodies early (it also checks content-length), and complements Axum's own DefaultBodyLimit, described in JSON and form bodies. The graceful shutdown lesson covers timeouts at the server level.

Request ids

A request id ties together the log lines of one request, and lets a user quote an id from an error message.

Rust
use tower_http::request_id::{MakeRequestUuid, PropagateRequestIdLayer, SetRequestIdLayer};
use axum::http::HeaderName;

let x_request_id = HeaderName::from_static("x-request-id");

let app = Router::new().route("/", get(home)).layer(
    tower::ServiceBuilder::new()
        .layer(SetRequestIdLayer::new(x_request_id.clone(), MakeRequestUuid))
        .layer(TraceLayer::new_for_http())
        .layer(PropagateRequestIdLayer::new(x_request_id)),
);

SetRequestIdLayer creates the id (or keeps the one the client or proxy sent), and PropagateRequestIdLayer copies it to the response. Note the order inside ServiceBuilder: top to bottom is execution order, so the id exists before tracing starts.

Other useful layers

Layer What it does
ServeDir, ServeFile static files, index.html, pre-compressed assets, range requests
CatchPanicLayer turns a panic in a handler into a 500 response instead of a dropped connection
SetResponseHeaderLayer adds headers such as x-content-type-options: nosniff or a strict-transport-security value
NormalizePathLayer trims trailing slashes (it must wrap the whole router, not be added with .layer)
SensitiveHeadersLayer hides authorization and cookie values from logs
ValidateRequestHeaderLayer simple bearer-token or accept-header validation

A sensible default stack

Rust
use tower::ServiceBuilder;

let middleware = ServiceBuilder::new()
    .layer(SetRequestIdLayer::new(x_request_id.clone(), MakeRequestUuid))
    .layer(TraceLayer::new_for_http())
    .layer(CatchPanicLayer::new())
    .layer(TimeoutLayer::new(Duration::from_secs(30)))
    .layer(CompressionLayer::new())
    .layer(cors)
    .layer(PropagateRequestIdLayer::new(x_request_id));

let app = Router::new().merge(routes()).layer(middleware);

Authentication goes on the routes that need it with route_layer, as described in the previous lesson.

Stand-in: how a CORS layer decides

CORS is a decision procedure over headers. The model below implements the preflight answer and the header added to ordinary responses for an allow-list of origins, including the credentials rule. Run it to see which requests would be permitted.

Rust Stand-in: CORS preflight and response headers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Notice that a rejected preflight is still a 200 with no access-control-allow-origin header: the server does not "refuse", the browser does, because the permission header is absent.

Stand-in: a timeout and a body limit

Layers such as RequestBodyLimitLayer and TimeoutLayer do simple things before and around your handler. This model simulates both with a pretend "work" duration, so you can see the status each guard produces and that the handler is skipped when a guard fails.

Rust Stand-in: body limit and timeout guards

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A browser sends an OPTIONS request with Access-Control-Request-Method before a JSON POST. What is it?

    Non-simple requests are preceded by a preflight asking which origins, methods and headers are allowed.
  2. 2. Which combination is invalid for CorsLayer?

    Browsers refuse a wildcard origin together with credentials, so tower-http panics at start-up if you try.
  3. 3. Which layer turns a panicking handler into a 500 response?

    CatchPanicLayer catches the panic and converts it into an error response.
  4. 4. In a ServiceBuilder, which layer runs first?

    ServiceBuilder reads top to bottom in execution order, unlike repeated Router::layer calls where the last is outermost.

Summary

  • tower-http provides ready-made layers behind Cargo features: TraceLayer, CorsLayer, CompressionLayer, TimeoutLayer, RequestBodyLimitLayer, request-id layers, ServeDir, CatchPanicLayer.
  • CorsLayer answers preflights itself; use explicit origins when credentials are involved.
  • Use ServiceBuilder to list layers in the order they execute; put request ids and tracing first.
  • Keep authentication on route_layer groups and your own rules in from_fn middleware.

Next: Extensions and Request IDs