Answer#
CompressionLayer::new() negotiates with the client through the standard Accept-Encoding header, so clients that do not ask for gzip still get the plain body.
use axum::{body::{to_bytes, Body}, http::{header, Request}, routing::get, Router};
use tower::ServiceExt;
use tower_http::compression::CompressionLayer;
async fn page() -> String { "<p>hello compression</p>".repeat(100) }
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(page)).layer(CompressionLayer::new());
for accept in [None, Some("gzip")] {
let mut b = Request::get("/");
if let Some(a) = accept { b = b.header(header::ACCEPT_ENCODING, a); }
let res = app.clone().oneshot(b.body(Body::empty()).unwrap()).await.unwrap();
let enc = res.headers().get(header::CONTENT_ENCODING).cloned();
let vary = res.headers().get(header::VARY).cloned();
let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
println!("accept-encoding {accept:?} -> content-encoding {enc:?}, vary {vary:?}, {} body bytes", body.len());
}
}accept-encoding None -> content-encoding None, vary Some("accept-encoding"), 2400 body bytes
accept-encoding Some("gzip") -> content-encoding Some("gzip"), vary Some("accept-encoding"), 67 body bytesThe page is 2400 bytes of repeated text, so it compresses extremely well here; real pages shrink by less. The numbers are from this one repeated string only and say nothing about your pages: measure your own responses.
tower-http = { version = "0.6.11", features = ["compression-gzip"] }Vary: accept-encoding is in the response so that caches keep the plain and compressed versions apart.
Common mistakes#
- Compressing files that are already compressed (JPEG, PNG, ZIP): CPU spent for little gain.
- Forgetting to enable the feature of the algorithm you want; without it the layer has nothing to offer.
Related questions#
Does the layer compress static files from ServeDir?#
Both are tower services, so the layer can be added around them; the thread on static files shows the file service.
Sources#
- tower-http,
compression: https://docs.rs/tower-http/0.6.11/tower_http/compression/index.html (read 2026-12-05)