compression
Express middleware that compresses responses with gzip or deflate based on the Accept-Encoding header.
Official Documentation ↗compression v1.7.x / Express 4.x / Node 18 LTS. Check the official docs for the latest API surface.Installation
npm install compressionpnpm add compressionyarn add compressionMethods
No methods match this filter.
Overview
compression compresses response bodies on the fly when the client advertises support, reducing transfer size for text-heavy payloads. It negotiates gzip or deflate from the Accept-Encoding header.
Core Methods
Apply the middleware globally, then tune with threshold, which skips tiny bodies, and filter, which decides per request. Compression is skipped for already-compressed content types.
Usage Notes
Use it for HTML, JSON and other text responses, and set a threshold so small payloads are not expanded by framing overhead. Verify that your proxy does not compress the same body twice.
Common Pitfalls
Compressing already-compressed binaries wastes CPU and can grow the payload. Mixing app compression with a compressing proxy can double-encode. ETag and content-length semantics change after compression.
FAQ
- Why are some responses not compressed?
- Compression is skipped for small responses below the threshold and for content types that are already compressed or non-compressible such as images. The filter function can also exclude requests.
- Can compression break caching or hashing?
- Compressed bodies differ from the original, so ETag values computed before compression may not match. Compute hashes on the uncompressed representation and let a proxy handle compression where possible.
- Should I compress at the app or the proxy?
- Edge proxies and CDNs often compress more efficiently and offload the CPU. Compress in the app when there is no proxy, or disable app compression to avoid double compression.
Report a problem with this API docOpens a pre-filled issue on GitHub.