Full answer
Text files such as HTML, CSS, JavaScript, JSON and SVG contain a lot of repetition, so they compress very well. Compression is one of the cheapest ways to cut transfer time.
How it works:
- The browser sends
Accept-Encoding: gzip, deflate, br, zstd(the exact list depends on the browser). - The server picks one it supports, compresses the body, and replies with
Content-Encoding: brorgzip. - The browser decompresses it before the page sees it. JavaScript code never handles this step.
- The response should include
Vary: Accept-Encoding, so that caches keep a separate copy for each encoding.
gzip and Brotli:
- gzip is supported everywhere and fast to compress.
- Brotli compresses text more tightly, usually by a noticeable amount, and it has a built-in dictionary of common web strings. High levels are slow, so static files are best compressed once at build time at a high level, and dynamic responses at a low or medium level.
- Browsers accept Brotli only over HTTPS. Newer encodings, such as Zstandard, are starting to appear, so check the support table before relying on them.
What not to compress again: JPEG, PNG, WebP, AVIF, MP4 and WOFF2 are already compressed. A second pass wastes CPU and can make the file a little bigger. Very small files are also not worth it, because the headers can cost more than the saving.
Compression is separate from minification. Minification changes the source text to make it shorter. Compression encodes the bytes. Use both.
To check, open the Network panel and compare the transferred size with the resource size, or look for the content-encoding header. A CDN usually does the compression for you, and it needs a rule that includes the right file types.
The script compresses a JSON list of 500 lessons with both methods, tries random bytes as a stand-in for an image, and runs a small server that picks Brotli when the client asks for it.
import http from 'node:http';
import { gzipSync, brotliCompressSync } from 'node:zlib';
import { randomBytes } from 'node:crypto';
const lessons = Array.from({ length: 500 }, (_, i) => ({ id: i, title: 'Lesson ' + i, level: ['easy', 'medium', 'hard'][i % 3] }));
const text = JSON.stringify(lessons);
const raw = Buffer.byteLength(text), gz = gzipSync(text).length, br = brotliCompressSync(text).length;
console.log('gzip smaller than raw:', gz < raw);
console.log('brotli smaller than gzip:', br < gz);
const photo = randomBytes(50000); // stands in for an already compressed image
console.log('random bytes saved under 1 percent:', gzipSync(photo).length > photo.length * 0.99);
const server = http.createServer((req, res) => {
const accepts = req.headers['accept-encoding'] ?? '';
res.setHeader('Vary', 'Accept-Encoding');
res.setHeader('Content-Type', 'application/json');
if (accepts.includes('br')) { res.setHeader('Content-Encoding', 'br'); res.end(brotliCompressSync(text)); }
else if (accepts.includes('gzip')) { res.setHeader('Content-Encoding', 'gzip'); res.end(gzipSync(text)); }
else res.end(text);
});
await new Promise((resolve) => server.listen(0, resolve));
const url = `http://localhost:${server.address().port}/`;
for (const enc of ['br', 'gzip', 'identity']) {
const res = await fetch(url, { headers: { 'accept-encoding': enc } });
const body = await res.json();
console.log(enc.padEnd(8), 'content-encoding:', res.headers.get('content-encoding') ?? 'none', 'items:', body.length);
}
server.close();Run with Node 24.22.1. The output matched the text in the answer in two runs.
Key points
- Accept-Encoding and Content-Encoding negotiate the compression.
- Brotli usually beats gzip on text. gzip is the safe fallback.
- Compress static files at build time at a high level.
- Do not compress images, video or WOFF2 again.
- Add Vary: Accept-Encoding, and compress in addition to minifying.
Common mistakes
- Thinking minification replaces compression.
- Compressing already compressed formats.
- Using the slowest Brotli level on every dynamic response.
- Forgetting Vary: Accept-Encoding behind a cache.
Follow-ups
- Why does the server need Vary: Accept-Encoding?
- How can compression interact with secrets in a response?
- How do you see the real transfer size in DevTools?
Tips
- Describe the header exchange in order.
- Say what you would not compress and why.