Gzip and deflate in the browser
CompressionStream and DecompressionStream
Baseline widely available
Chrome80
Edge80
Firefox113
Safari16.4
Features it needs
- Compression streamsWidely available
pako ships a JavaScript port of zlib, and lz-string implements its own compression scheme, both to compress data before an upload or a localStorage write. CompressionStream and DecompressionStream do the same job as a platform-native stream: pipe bytes in, get gzip or deflate bytes out, with no compression library in the bundle.
When this applies
Compressing or decompressing bytes with gzip or deflate before sending or storing them.
The native approach
const compressed = new Response(
new Blob([data]).stream().pipeThrough(new CompressionStream("gzip")),
);
const bytes = await compressed.arrayBuffer();When the dependency is still right
An answer that always says "the platform covers it" is worse than no answer. These are the cases where this one does not hold.
- You need brotli. CompressionStream takes gzip, deflate and deflate-raw and nothing else, so brotli is a library either way.
- You need lz-string's specific format, such as its base64 or UTF-16 encodings meant for squeezing compressed data into localStorage or a URL. CompressionStream only speaks gzip, deflate, and raw deflate.
- You need synchronous compression of a small string with no stream setup. CompressionStream is stream-based, so a few lines of glue code are still required at the call site.