Skip to content
jshacks.dev
Node.js

Serve a gzipped response with zlib

Compress an HTTP response with zlib.createGzip in a plain Node.js 24 server, only when the client sends Accept-Encoding gzip, with the Vary header set.

2 min read
Summarize in AI

Behind no proxy, a Node.js server sends text uncompressed unless you compress it. The code is short; the headers are where it usually goes wrong.

server.mjsJavaScript
import http from 'node:http';
import zlib from 'node:zlib';
import { createReadStream } from 'node:fs';
import { pipeline } from 'node:stream';

http.createServer((req, res) => {
  const gzip = /\bgzip\b/.test(req.headers['accept-encoding'] ?? '');
  res.setHeader('Content-Type', 'application/json');
  res.setHeader('Vary', 'Accept-Encoding');
  if (gzip) res.setHeader('Content-Encoding', 'gzip');

  const body = createReadStream('report.json');
  const onError = (err) => err && res.destroy(err);
  if (gzip) pipeline(body, zlib.createGzip(), res, onError);
  else pipeline(body, res, onError);
}).listen(3000);
Text
$ curl -s -D - -o /dev/null -H 'Accept-Encoding: gzip' localhost:3000
HTTP/1.1 200 OK
Content-Type: application/json
Vary: Accept-Encoding
Content-Encoding: gzip
Date: Sun, 15 Nov 2026 10:00:00 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Transfer-Encoding: chunked

Compression happens only when the request's Accept-Encoding lists gzip, and Content-Encoding: gzip tells the client to decode it. Vary: Accept-Encoding is the header people forget: without it a CDN or browser cache can store the gzipped copy and serve it to a client that never asked for gzip. The length is unknown while compressing, so Node.js falls back to chunked encoding. The date will be the time of your request. See zlib for HTTP.

Skip it for images, video and archives, which are compressed already, and for tiny bodies, where the gzip header outweighs the saving. If nginx or a CDN sits in front, let it compress and keep the CPU work out of your process.

Taggednode 24
Share

More snippets

Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

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.