http-response-compression
A Tower middleware layer for compressing HTTP response bodies.
Features
- Supports Gzip, Brotli, and Zstd compression
- Automatic codec selection based on
Accept-Encodingheader - Configurable minimum body size threshold (default: 860 bytes)
- Streaming support with flush control for SSE and gRPC-web
- Preserves trailers through compression
Usage
use CompressionLayer;
use ServiceBuilder;
let service = new
.layer
.service;
With custom minimum size:
let service = new
.layer
.service;
Compression Rules
The middleware will not compress responses when:
- No supported
Accept-Encodingis present in the request Content-Encodingheader is already setContent-Rangeheader is present (range responses)Content-Typeisimage/*(exceptimage/svg+xml)Content-Typeisapplication/grpc(exceptapplication/grpc-web)Content-Lengthis below the minimum size threshold
The middleware will always flush after each chunk when:
X-Accel-Buffering: noheader is presentContent-Typeistext/event-streamContent-Typeisapplication/grpc-web
Response Modifications
When compression is applied:
Content-Encodingheader is set to the codec usedContent-Lengthheader is removed (compressed size is unknown)Accept-Rangesheader is removedVaryheader includesAccept-Encoding
License
MIT