Skip to content
jshacks.dev
Performance

Use HTTP compression in Express

Compress text responses in Express 5 with the compression middleware, which reads Accept-Encoding and skips small or already compressed bodies.

1 min read
Summarize in AI

JSON, HTML and CSS shrink a lot when compressed, and every browser asks for it. The compression middleware turns it on in one line.

Shell
npm install compression
server.jsJavaScript
import express from 'express';
import compression from 'compression';

const app = express();
app.use(compression({ threshold: 1024 }));

app.get('/items', (req, res) => {
  res.json(Array.from({ length: 500 }, (_, i) => ({ id: i, name: `Item ${i}` })));
});

app.listen(3000);
Text
$ curl -s -D - -o /dev/null -H 'Accept-Encoding: gzip' localhost:3000/items | grep -i -E 'content-encoding|vary'
Content-Encoding: gzip
Vary: Accept-Encoding

The middleware looks at Accept-Encoding, compresses the body and sets Content-Encoding and Vary. The threshold option skips bodies under 1024 bytes, where the header overhead outweighs the saving. It also skips content types that are not compressible.

Put it before the routes it should cover. If a reverse proxy or CDN already compresses, doing it twice wastes CPU, so enable it in one place. Compression of a response containing both a secret and attacker-controlled text can leak the secret in some TLS setups (the BREACH attack), so be careful with secrets in compressed HTML. See the compression package.

Also inNode.js
Share

More snippets

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.