Skip to content
jshacks.dev
Performance

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.

1 min read
Summarize in AI

Brotli usually produces smaller text payloads than gzip. Node.js ships it in node:zlib, so no package is needed.

server.jsJavaScript
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);
Text
$ curl -sI -H 'Accept-Encoding: br' http://localhost:3000 | grep -i content-encoding
content-encoding: br

Quality 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.

Also inNode.js
Taggednode 24
Share

More snippets

Testing

Group tests with describe in node test

Group related tests with describe and it from node:test, nest suites, and run setup with beforeEach, all without installing a framework.

1 min read
Performance

Time code with performance.now

Time a block of code with performance.now, which returns a monotonic high-resolution timestamp in milliseconds, and avoid the clock jumps Date.now can have.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.