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.
JSON, HTML and CSS shrink a lot when compressed, and every browser asks for it. The compression middleware turns it on in one line.
npm install compressionimport 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);$ curl -s -D - -o /dev/null -H 'Accept-Encoding: gzip' localhost:3000/items | grep -i -E 'content-encoding|vary'
Content-Encoding: gzip
Vary: Accept-EncodingThe 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.