A big log or JSON export uploads faster when it is compressed first, and I would rather not ship a compression library for that. Browsers have a gzip stream built in.
async function gzip(text) {
const stream = new Blob([text]).stream()
.pipeThrough(new CompressionStream("gzip"));
return new Response(stream).blob();
}
const packed = await gzip(JSON.stringify(bigData));
await fetch("/api/upload", {
method: "POST",
headers: { "Content-Type": "application/gzip" },
body: packed,
});
CompressionStream is a transform stream: data goes in one side and compressed bytes come out the other. A Blob gives you a readable stream, pipeThrough runs it through the compressor, and wrapping the result in a Response is a short way to collect a stream into a blob. The word “hello ” repeated 1000 times (6000 bytes) comes out at 53 bytes. Real data compresses less, but JSON usually shrinks a lot.
The formats are "gzip", "deflate" and "deflate-raw". DecompressionStream reverses it, for example to read a .gz file a user picks.
Your server has to expect it. I’d send a gzip file as the body with its own content type; sending JSON with Content-Encoding: gzip as a request header only works if the server decompresses request bodies, which many do not by default. Support: Chrome 80, Firefox 113 and Safari 16.4.
Further reading: MDN: CompressionStream, MDN: Compression Streams API