Compress responses with Brotli in Node.js
Compress a response body with Brotli using node:zlib brotliCompressSync and send Content-Encoding br, after checking the client sent Accept-Encoding br.
Brotli usually produces smaller text payloads than gzip. Node.js ships it in node:zlib, so no package is needed.
import http from 'node:http';
import { brotliCompressSync, constants } from 'node:zlib';
const body = JSON.stringify({ items: Array.from({ length: 200 }, (_, i) => ({ id: i, name: `Item ${i}` })) });
http.createServer((req, res) => {
const accepts = req.headers['accept-encoding'] ?? '';
res.setHeader('content-type', 'application/json');
res.setHeader('vary', 'accept-encoding');
if (accepts.includes('br')) {
const compressed = brotliCompressSync(body, {
params: { [constants.BROTLI_PARAM_QUALITY]: 5 },
});
res.setHeader('content-encoding', 'br');
res.end(compressed);
} else {
res.end(body);
}
}).listen(3000);$ curl -sI -H 'Accept-Encoding: br' http://localhost:3000 | grep -i content-encoding
content-encoding: brQuality runs from 0 to 11. The default of 11 gives the smallest output but is slow, so quality 4 to 6 suits dynamic responses; save the top level for files compressed once at build time.
Vary: Accept-Encoding stops caches from serving a compressed body to a client that cannot read it. Compress only text formats: images and archives are already compressed. In production a reverse proxy often does this job instead. See zlib Brotli in the Node.js docs.