How to gzip and download text or files in React with CompressionStream
Browsers include CompressionStream, so you can gzip text or files without adding a library. Read a Blob with stream(), pass it through CompressionStream, and save the resulting Blob with an a element that has a download attribute.
I built a React component that saves typed text and a selected file as .gz. I then expanded the saved files with the gzip command and confirmed they returned to the original contents.
The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used react / react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx with tsc, transformed it with esbuild, and ran it as a development build. I clicked the buttons with Playwright to receive the downloads, and checked the files with gzip 1.12. I did not test Firefox, Safari, smartphone browsers, production builds, or files larger than 50MB.

Pass a Blob through CompressionStream to make a gzip Blob
This is the function that compresses. It takes both text and files as a Blob (as noted in MDN's File description, File is a kind of Blob, so you can pass it directly).
// gzip.ts
export async function gzipBlob(
input: Blob,
onProgress?: (doneBytes: number) => void,
): Promise<Blob> {
let done = 0;
// Count the bytes that pass before compression and report them as progress
const counter = new TransformStream<Uint8Array<ArrayBuffer>, Uint8Array<ArrayBuffer>>({
transform(chunk, controller) {
done += chunk.byteLength;
onProgress?.(done);
controller.enqueue(chunk);
},
});
const stream = input
.stream()
.pipeThrough(counter)
.pipeThrough(new CompressionStream('gzip'));
const gz = await new Response(stream).blob();
return new Blob([gz], { type: 'application/gzip' });
}
Blob.stream() returns a ReadableStream that reads the contents little by little. Connecting it to a CompressionStream with pipeThrough() makes compressed bytes flow out. To combine the output into a single Blob, use new Response(stream).blob(). This pattern is the same as the example in the Compression Standard specification that decompresses a Blob.
The MIME type (type) of a Blob created with Response.blob() is the value of the response's Content-Type. With new Response(stream), where only a stream is passed, type was an empty string in Chromium 153. So at the end, I wrap the result in a new Blob with application/gzip.
The counter in the middle is only for showing progress. If you don't need progress, input.stream().pipeThrough(new CompressionStream('gzip')) is enough.
When compressing text, create a Blob with new Blob([text]). As noted in MDN's Blob() constructor description, strings are written as UTF-8. When I expanded the saved file, the Japanese text came back exactly as it was.
Using only Uint8Array as the type argument causes a type error
When I put a TransformStream typed as <Uint8Array, Uint8Array> in between, the type check in TypeScript 7.0.2 flagged the place where CompressionStream is passed (the error output is excerpted).
error TS2345: Argument of type 'CompressionStream' is not assignable to parameter of type 'ReadableWritablePair<Uint8Array<ArrayBuffer>, Uint8Array<ArrayBufferLike>>'.
Types of property 'writable' are incompatible.
Type 'WritableStream<BufferSource>' is not assignable to type 'WritableStream<Uint8Array<ArrayBufferLike>>'.
A Uint8Array written without a type argument means Uint8Array<ArrayBufferLike>, and that type does not match the BufferSource that CompressionStream accepts. Writing Uint8Array<ArrayBuffer>, as in the code above, removed the error. Connecting Blob.stream() directly to CompressionStream without the counter in between also produced no error.
Save with the download attribute of an a element
The finished Blob is turned into an object URL, given to an a element, and clicked to save.
// gzip.ts (continued)
export function saveBlob(blob: Blob, filename: string): void {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
According to MDN's a element description, the download attribute works with blob: URLs from the same origin. Release an object URL when you are done with it using URL.revokeObjectURL(). In Chromium 153, the file was saved in full even though I released the URL right after click().
For the filename, I add .gz to the original name. The first 10 bytes of the saved gzip were 1f 8b 08 00 00 00 00 00 00 03. For comparison, when I compressed the same text with the gzip command, I got 1f 8b 08 08 80 bb ef 6a 00 03, and the file command showed the original name (memo.txt) and the modification time. For the .gz made in Chromium, the file command shows neither. In other words, the gzip does not contain the original file name or modification time.
So when I renamed the file to renamed.txt.gz and expanded it with gunzip -N, it became renamed.txt. The name used when expanding is determined by the filename of the .gz after renaming.
The React component
I added one button each to the text input and the file picker. While compressing, the component shows progress, and when it finishes, it shows the sizes before and after compression.
// GzipDownload.tsx
import { useState } from 'react';
import { gzipBlob, saveBlob } from './gzip';
type Status =
| { kind: 'idle' }
| { kind: 'working'; done: number; total: number }
| { kind: 'done'; filename: string; before: number; after: number }
| { kind: 'error'; message: string };
const kb = (n: number) => `${(n / 1024).toFixed(1)} KB`;
export function GzipDownload() {
const [text, setText] = useState('');
const [file, setFile] = useState<File | null>(null);
const [status, setStatus] = useState<Status>({ kind: 'idle' });
async function run(source: Blob, filename: string) {
setStatus({ kind: 'working', done: 0, total: source.size });
try {
const gz = await gzipBlob(source, (done) =>
setStatus({ kind: 'working', done, total: source.size }),
);
saveBlob(gz, filename);
setStatus({ kind: 'done', filename, before: source.size, after: gz.size });
} catch (e) {
setStatus({ kind: 'error', message: String(e) });
}
}
const working = status.kind === 'working';
return (
<div className="demo">
<label>
文章
<textarea value={text} onChange={(e) => setText(e.target.value)} rows={5} />
</label>
<button
disabled={working || text === ''}
onClick={() => run(new Blob([text], { type: 'text/plain' }), 'memo.txt.gz')}
>
文章を gzip で保存
</button>
<label>
ファイル
<input type="file" onChange={(e) => setFile(e.target.files?.[0] ?? null)} />
</label>
<button
disabled={working || file === null}
onClick={() => file && run(file, `${file.name}.gz`)}
>
ファイルを gzip で保存
</button>
<p role="status">
{status.kind === 'working' &&
`圧縮中(${Math.floor((status.done / Math.max(status.total, 1)) * 100)}%)`}
{status.kind === 'done' &&
`${status.filename} を保存しました(${kb(status.before)} → ${kb(status.after)})`}
{status.kind === 'error' && `失敗しました:${status.message}`}
</p>
</div>
);
}
When I selected and saved a 50MB log file, the status text went "Compressing (0%)", then "Compressing (7%)", and on to "Compressing (100%)". Finally it showed "big.log.gz saved (51200.0 KB → 5192.7 KB)". The progress message changed 26 times, and 376 milliseconds passed from the first progress message to the final "saved" message.
Progress increases each time Blob.stream() delivers one chunk. When I read the same 50MB file, the chunks were 64KB (65,536 bytes) at first, the largest was 1,507,328 bytes, and there were 601 chunks in total.
How much smaller it gets
I compared the sizes of .gz files made with CompressionStream and those made with each level of the gzip command (-1, -6, -9). For the gzip command, I added -n, which leaves out the name and time. The units are bytes.
| Original file | Original size | CompressionStream | gzip -1 | gzip -6 | gzip -9 |
|---|---|---|---|---|---|
| CSV text containing Japanese (about 1,000 lines) | 22,641 | 4,118 | 5,083 | 4,120 | 3,852 |
| Log file (about 50MB) | 52,428,835 | 5,317,288 | 6,044,814 | 5,339,678 | 5,103,326 |
| File of random numbers (1MB) | 1,048,576 | 1,048,919 | 1,048,754 | 1,048,754 | 1,048,754 |
In Chromium, the results for both the CSV text and the log were close to gzip -6. The CompressionStream constructor takes only the format name (see the CompressionStream definition in the specification), and it has no argument for choosing a compression level.
The file of random numbers grew by 343 bytes when compressed. The gzip command also made it larger than the original at every level. Data with no repetition, such as random numbers, did not get smaller with gzip.
When I compressed the same string twice in Chromium 153, the byte sequences were exactly the same. As seen earlier, this is because no date and time go into the header.
Other formats you can pass
I changed the format name passed to CompressionStream and tried each one in Chromium 153.
| Format | Result |
|---|---|
gzip |
Works |
deflate |
Works |
deflate-raw |
Works |
brotli |
TypeError (Unsupported compression format) |
zstd |
TypeError (Unsupported compression format) |
zip |
TypeError (Unsupported compression format) |
brotli is in the specification, and MDN's CompressionStream() constructor description also lists zstd. However, the compatibility table on the same page shows that, at the time of writing, Chrome does not yet support either brotli or zstd. brotli is available from Firefox 147 and Safari 18.4. If you only need to make gzip files, gzip is available from Chrome 80, Firefox 113, and Safari 16.4.
zip is not among the format names. If you want to combine several files into one, you need a library such as JSZip, which I used in another article, "How to bundle multiple files into a ZIP and download them in React."
Decompressing in the browser
With the reverse direction, DecompressionStream, you can expand a .gz in the browser.
const text = await new Response(
gz.stream().pipeThrough(new DecompressionStream('gzip')),
).text();
A 3,000-byte text made by joining こんにちは、gzip。🐈 100 times became 77 bytes, and the string restored with DecompressionStream matched the original string.





