Skip to content
jshacks.dev
Browser

The Compression Streams API

How CompressionStream and DecompressionStream gzip and inflate data in JavaScript with no library: Blobs, fetch bodies, files and size trade-offs.

8 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, JavaScript, NGINX, Swagger and Postman logos.

Compressing data used to be a library problem. If a page wanted to gzip a payload before uploading it, shrink a large JSON blob before storing it in IndexedDB or read a .gz file the user dropped on it, it pulled in pako or fflate, tens of kilobytes of JavaScript to do something the browser already does internally for every HTTP response. The Compression Streams API exposes that built-in capability. CompressionStream and DecompressionStream are transform streams: bytes go in one end and compressed, or decompressed, bytes come out the other, in chunks, with no library, no dependency and no main-thread blocking for the compression itself. This post explains how the Compression Streams API works: the supported formats, how to compress and decompress data with pipeThrough(), helpers for strings and Blobs, how to use it with fetch(), files and IndexedDB, how to handle errors for corrupt input, what it costs and when compression helps, what the API does not do, and how to test it. It is defined by the Compression Standard, documented on MDN, and supported in all current browsers and in Node.js, Deno and Bun.

The formats

The constructors take a format name: "gzip", "deflate" or "deflate-raw". They are three framings of the same DEFLATE algorithm. gzip is the file format of .gz files and the standard Content-Encoding: gzip, with a header and a CRC check. deflate is the zlib format, with a smaller header and an Adler-32 check, and it is what the HTTP Content-Encoding: deflate means. deflate-raw is the bare stream without a header or a checksum, which is what ZIP archives and many binary formats embed. Choose gzip unless something else dictates, since it is the most interoperable and has an integrity check.

basic.jsJavaScript
const gzip = new CompressionStream("gzip");
const gunzip = new DecompressionStream("gzip");

console.log(gzip.readable instanceof ReadableStream);
console.log(gzip.writable instanceof WritableStream);
console.log(gunzip.readable instanceof ReadableStream);

try {
  new CompressionStream("zip");
} catch (error) {
  console.log(error.name);
}
Text
true
true
true
TypeError

Each object has a writable side to push bytes into and a readable side to pull the result from, which is the transform stream shape. An unknown format name throws a TypeError. Newer implementations are adding formats such as zstd and brotli, which would follow the same pattern, so check the compatibility table and use feature detection if you want them.

Compressing a string

The simplest way to use a transform stream is to pipe a readable through it. A string becomes bytes with TextEncoder, a Blob, which has a stream() method, or a Response.

compress.jsJavaScript
async function gzipString(text) {
  const stream = new Blob([text]).stream().pipeThrough(new CompressionStream("gzip"));
  return new Response(stream).arrayBuffer();
}

const input = "hello ".repeat(1000);
const compressed = await gzipString(input);

console.log(input.length, compressed.byteLength < 100);
Text
6000 true

Six thousand characters of repeated text compress to well under a hundred bytes. The exact size depends on the implementation, and this input is as repetitive as input gets, so text in the real world compresses by a factor of two to ten and already-compressed formats such as JPEG, PNG, MP4 and ZIP do not compress at all. The Response object is a convenient consumer: new Response(stream) turns any ReadableStream into something you can read with arrayBuffer(), blob() or text().

Decompressing

Decompression is the mirror image. Feed compressed bytes and read the text back.

decompress.jsJavaScript
async function gunzipToString(buffer) {
  const stream = new Blob([buffer]).stream().pipeThrough(new DecompressionStream("gzip"));
  return new Response(stream).text();
}

const text = await gunzipToString(compressed);
console.log(text.length, text.slice(0, 12));
Text
6000 hello hello 

A round trip returns the exact original, which makes a good unit test. The text() method decodes as UTF-8, so for binary data use arrayBuffer() instead. Both directions stream: the work happens as chunks flow, so memory use stays modest even for large inputs when you consume the output incrementally instead of collecting it into one buffer.

Helpers worth keeping

A pair of small functions covers most uses, and they make the calling code read clearly.

helpers.jsJavaScript
export async function gzip(input) {
  const stream = new Blob([input]).stream().pipeThrough(new CompressionStream("gzip"));
  return new Uint8Array(await new Response(stream).arrayBuffer());
}

export async function gunzip(bytes) {
  const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"));
  return new Uint8Array(await new Response(stream).arrayBuffer());
}

const packed = await gzip(JSON.stringify({ items: Array.from({ length: 200 }, (_, i) => ({ id: i, name: `item ${i}` })) }));
const unpacked = JSON.parse(new TextDecoder().decode(await gunzip(packed)));

console.log(packed.length < 2000, unpacked.items.length);
Text
true 200

Uploading compressed bodies

A fetch() request body can be a stream in browsers that support streaming uploads, but the more portable use is to compress to a Blob first and send that, with a Content-Encoding header if the server decompresses request bodies, which many do not by default. Check that your server handles it, or use your own header and endpoint convention.

upload.jsJavaScript
async function uploadGzipped(url, data) {
  const compressed = await new Response(
    new Blob([JSON.stringify(data)]).stream().pipeThrough(new CompressionStream("gzip")),
  ).blob();

  const response = await fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json", "Content-Encoding": "gzip" },
    body: compressed,
  });
  console.log(response.status);
}

uploadGzipped("/api/logs", { events: new Array(500).fill({ type: "click" }) });
Text
200

This is useful for large telemetry and log batches, where the payload is repetitive JSON that compresses well and the upload is on a slow mobile link. For small bodies, compression costs more than it saves, since the overhead of the headers and the CPU time exceed the bytes you remove, so apply it above a threshold such as a few kilobytes.

Reading compressed files

When a user selects a .gz file, the File is a Blob, so file.stream() gives a readable stream that you can pipe through DecompressionStream. For a large file, process the output incrementally with a reader or an async iteration, and the whole file never sits in memory.

file.jsJavaScript
async function countLines(file) {
  const stream = file
    .stream()
    .pipeThrough(new DecompressionStream("gzip"))
    .pipeThrough(new TextDecoderStream());

  let lines = 0;
  let carry = "";

  for await (const chunk of stream) {
    const parts = (carry + chunk).split("\n");
    carry = parts.pop();
    lines += parts.length;
  }
  return lines + (carry ? 1 : 0);
}

const sample = new File([await gzip("a\nb\nc\n")], "sample.txt.gz");
console.log(await countLines(sample));
Text
3

TextDecoderStream converts the bytes into strings, handling multi-byte characters that fall across chunk boundaries correctly, and the loop keeps a carry for the partial last line of each chunk. Async iteration over a ReadableStream works in current browsers, and in older ones you can use getReader() and a loop.

Storing compressed data

Compressing large JSON before putting it into IndexedDB or localStorage-like stores can save space, since storage quotas are finite. Store the compressed bytes as a Blob or Uint8Array in IndexedDB, which handles binary data natively. localStorage stores only strings, so you would have to base64-encode the bytes, which gives back about a third of the savings, and so IndexedDB is the better target.

store.jsJavaScript
async function saveCompressed(db, key, value) {
  const bytes = await gzip(JSON.stringify(value));
  return new Promise((resolve, reject) => {
    const request = db.transaction("cache", "readwrite").objectStore("cache").put(bytes, key);
    request.onsuccess = () => resolve(bytes.length);
    request.onerror = () => reject(request.error);
  });
}
Text
(the compressed bytes are stored under the key and the stored size is returned)

Errors and corrupt input

Decompression fails if the input is not valid data for the format, and the stream errors with a TypeError. When you read the output, that error comes out of the promise or the loop, so handle it.

errors.jsJavaScript
try {
  const bad = new Uint8Array([1, 2, 3, 4, 5]);
  await gunzip(bad);
} catch (error) {
  console.log(error.name);
}
Text
TypeError

A truncated stream, for instance a file cut short, also errors at the end, because the checksum or the end marker is missing. Recent implementations are strict about trailing data after a valid gzip member, and may reject it, so do not rely on concatenated or padded input being accepted everywhere. For untrusted data, limit the output size you are willing to produce, since a small compressed input can expand to gigabytes, the decompression bomb, and read the stream with a counter that cancels when it passes a limit.

limit.jsJavaScript
async function gunzipLimited(bytes, maxBytes) {
  const reader = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip")).getReader();
  const chunks = [];
  let total = 0;

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    total += value.byteLength;
    if (total > maxBytes) {
      await reader.cancel();
      throw new RangeError("decompressed data is too large");
    }
    chunks.push(value);
  }
  return new Blob(chunks);
}

const small = await gunzipLimited(await gzip("x".repeat(100)), 1000);
console.log(small.size);
Text
100

What it does not do

There is no compression level option, so you cannot trade speed for size, and there is no dictionary support, no ZIP archive handling and no encryption. ZIP needs a container format on top, which is a library job, or use deflate-raw and write the ZIP structure yourself if you have the patience. Brotli and Zstandard are not in the baseline, so for the best ratios in the browser you may still reach for a WebAssembly build of those codecs. For HTTP responses, you do not need this API at all: the browser decompresses Content-Encoding automatically, and the server should compress responses with gzip or Brotli at the edge.

Performance

Compression runs off the main thread in implementations, in a native code path, so it is faster than a JavaScript library and does not block rendering for the compression itself, although the data moving through your own code does take time on the main thread. For very large work, run it in a worker to keep everything off the main thread. Measure before you decide that compression pays: compress, check the ratio and the time on real data from your application, and apply it only when the saving is worth the CPU.

Testing

A round trip test is the simplest and most valuable: compress, decompress, compare. Add a case for the empty input, for one with multi-byte characters and for corrupt bytes. In Node.js, the same classes are available as globals in current versions and also through node:stream/web, so the tests can run there without a browser.

test.jsJavaScript
const samples = ["", "plain", "héllo wörld 🌍", "x".repeat(100000)];

for (const sample of samples) {
  const out = new TextDecoder().decode(await gunzip(await gzip(sample)));
  console.log(out === sample);
}
Text
true
true
true
true

Pitfalls

Compressing tiny payloads. Compressing already-compressed data. Assuming the server accepts a compressed request body. Collecting a huge stream into memory when you could process it in chunks. Forgetting to handle errors for corrupt input. Decompressing untrusted data with no size limit. Mixing up deflate and deflate-raw, which produces errors that look like corruption. And expecting a ZIP file from gzip.

Also inAsync
Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.