How to Implement HTTP Compression Negotiation
Negotiate Accept-Encoding, choose between Brotli and gzip, compress the right response types, and avoid compressing already-compressed data.
On this page
Introduction
Most API responses and web pages are text, and text compresses well. Turning on compression is one of the cheapest bandwidth wins available, often reducing a JSON payload by seventy percent or more. But compression is a negotiation, not a switch: the client advertises what it can decode, the server chooses an algorithm, and the response declares what it did. Getting the negotiation wrong means a client receives bytes it cannot decode, and getting the content-type choice wrong means wasting CPU to make a file larger.
This tutorial implements compression negotiation for a Node.js service. It covers reading Accept-Encoding, choosing between Brotli and gzip, deciding which responses to compress at all, setting the headers that keep caches correct, and testing the matrix. The examples use zlib, but the protocol behavior is the same in any runtime.
Read Accept-Encoding correctly
Accept-Encoding is a list of content codings the client can decode, each with an optional quality value. The value gzip, br means the client accepts both; br;q=1.0, gzip;q=0.8 means it prefers Brotli. The special token identity means no encoding. A coding with q=0 is a refusal: gzip;q=0, br means the client can decode Brotli but explicitly not gzip. And an empty Accept-Encoding header means the client can decode nothing but identity.
When the header is absent entirely, the specification permits the server to assume any encoding is acceptable, but the safe practice is to send identity unless you are confident. Never base the decision on a substring check for gzip that ignores the br token’s quality and position; parse the list properly so a refusal is respected.
function parseAcceptEncoding(header) {
if (header === undefined) return new Map([['identity', 1]]);
const map = new Map();
for (const part of String(header).split(',')) {
const [coding, ...params] = part.trim().split(';');
let q = 1;
for (const p of params) {
const [k, v] = p.trim().split('=');
if (k === 'q') q = Number(v);
}
map.set(coding.trim().toLowerCase(), Number.isFinite(q) ? q : 1);
}
return map;
}
function chooseEncoding(header, supported) {
const prefs = parseAcceptEncoding(header);
let best = 'identity';
let bestQ = prefs.get('identity') ?? 1;
for (const enc of supported) { // e.g. ['br', 'gzip']
const q = prefs.get(enc);
if (q !== undefined && q > 0 && q >= bestQ) { best = enc; bestQ = q; }
}
return best;
}
Choose the algorithm and the responses
Brotli generally produces smaller output than gzip for text and is supported by every current mainstream browser. Send it when the client accepts br, fall back to gzip for older clients, and leave identity for the rest. The choice should also consider cost: Brotli at a high quality setting is CPU-intensive, so precompress static assets at build time and use a lower quality for dynamic responses.
Compress the content types that benefit: JSON, HTML, CSS, JavaScript, SVG, and plain text. Leave already-compressed formats alone, including JPEG, PNG, WebP, gzip archives, and video. Compressing an image wastes CPU and can enlarge it, because the compression format sees high-entropy bytes and cannot find structure. Also skip very small bodies, where the overhead of the encoding can exceed the savings and the header becomes noise.
const COMPRESSIBLE = /^(text\/|application\/(json|javascript|xml|.+\+json|.+\+xml)|image\/svg\+xml)/;
function shouldCompress(contentType, bodyBuffer) {
if (!contentType || !COMPRESSIBLE.test(contentType)) return false;
return bodyBuffer.length > 1024; // skip tiny bodies
}
Set the headers that keep caches honest
When the body is encoded, set Content-Encoding to the chosen coding, such as br or gzip. Add Vary: Accept-Encoding so shared caches store separate copies per encoding and never serve a Brotli body to a client that cannot decode it. If you had set Content-Length before compressing, remove or update it, because the compressed length differs; either recompute it or let the framework chunk the response.
Compress before computing an ETag, or hash the compressed bytes, so the validator and the transmitted bytes agree. If you hash the uncompressed body but send a compressed one, the ETag is still valid semantically but the same ETag will appear on different encodings, which requires a weak validator. Consistency across the pipeline avoids confusing caches.
import { createServer } from 'node:http';
import { brotliCompressSync, gzipSync } from 'node:zlib';
createServer((req, res) => {
const body = Buffer.from(JSON.stringify({ items: new Array(200).fill('x') }));
const enc = chooseEncoding(req.headers['accept-encoding'], ['br', 'gzip']);
const headers = { 'content-type': 'application/json', vary: 'Accept-Encoding' };
if (enc === 'br') {
const out = brotliCompressSync(body);
res.writeHead(200, { ...headers, 'content-encoding': 'br', 'content-length': out.length });
res.end(out);
return;
}
if (enc === 'gzip') {
const out = gzipSync(body);
res.writeHead(200, { ...headers, 'content-encoding': 'gzip', 'content-length': out.length });
res.end(out);
return;
}
res.writeHead(200, { ...headers, 'content-length': body.length });
res.end(body);
}).listen(3000);
Combine with TLS and CDNs
Compression interacts with TLS through a historical attack where compressed sizes leak plaintext through chosen-input compression. Do not compress responses that reflect secret values alongside attacker-controlled input, and do not enable shared-dictionary compression across users. Breach-style attacks are rare in practice but real, so keep secrets out of compresseable responses that echo user input.
A CDN can store per-encoding copies if Vary is correct and compress on the fly at the edge, which frees your origin CPU. Ensure the origin and the edge agree on which encodings they support so a request does not bounce without compression or double-compress. Double compression, where a gzip body is gzipped again, adds overhead and produces a body the client cannot decode.
Test negotiation and non-compression
Test the negotiation matrix: a client that accepts br gets Brotli, one that accepts only gzip gets gzip, one with gzip;q=0 gets identity, and one with no Accept-Encoding gets identity. Assert Vary: Accept-Encoding is present on every compressible response. Then assert that a PNG response is not encoded, which catches a content-type filter that is too broad.
curl -s -H 'Accept-Encoding: br' -o out.br -w '%{size_download} %{content_type}\n' http://localhost:3000/data
curl -s -H 'Accept-Encoding: gzip' -o out.gz -w '%{size_download}\n' http://localhost:3000/data
curl -s -H 'Accept-Encoding: gzip;q=0' -D - -o /dev/null http://localhost:3000/data | grep -i -E 'content-encoding|vary'
Common pitfalls
Ignoring quality values, compressing already-compressed formats, forgetting Vary, leaving a stale Content-Length after compressing, double-compressing a body an upstream already encoded, and compressing secrets alongside user input are the recurring mistakes. The negotiation tests catch the first four, and explicit content-type filters plus a check for an existing Content-Encoding catch the rest.
Conclusion
Compression is a negotiation followed by a header change. Parse Accept-Encoding with quality values, prefer Brotli with a gzip fallback, compress only compressible and non-trivial bodies, set Content-Encoding and Vary: Accept-Encoding, and fix Content-Length. Self-check by asserting the chosen coding per Accept-Encoding value and by confirming a binary type is left untouched. Done correctly, compression is invisible to clients and expensive only when it should be.
Sources: MDN: Accept-Encoding header, RFC 9110: Content codings, MDN: Content-Encoding header.
FAQ
- Brotli or gzip?
- Brotli usually compresses text smaller than gzip at the same or better speed for static content, and every modern browser accepts it. Send Brotli when br appears in Accept-Encoding, fall back to gzip, and keep an uncompressed path for clients that support neither.
- Should I compress images?
- No. JPEG, PNG, WebP, and most video formats are already compressed, so re-compressing wastes CPU and may even grow the payload. Compress the compressible text types and leave binary formats alone.
Report a problem with this articleOpens a pre-filled issue on GitHub.