compression

raw JSON →
1.7.5 verified Sat Apr 25 auth: no javascript

Node.js compression middleware for Express/Connect that supports gzip, deflate, and brotli response compression. Current stable version is 1.8.1, released March 2025, with a moderate release cadence. Key differentiators: built-in brotli support (requires Node >= v11.7.0 or v10.16.0), automatic filtering based on Content-Type via the compressible package, and flexible configuration of compression levels and memory usage. It is part of the Express.js ecosystem and is widely used with Express and plain Node HTTP servers.

error Error: Compression requires a valid Accept-Encoding header
cause Request without Accept-Encoding header
fix
Ensure the client sends Accept-Encoding header, e.g., 'gzip, deflate'.
error TypeError: Cannot read property 'pipe' of undefined
cause Response body is not a stream or is null
fix
Make sure the response body is a stream or string/buffer.
error Error: write after end
cause Response already sent before compression completes
fix
Ensure no early res.end() calls; use res.write() properly.
gotcha Brotli compression requires Node.js >= v11.7.0 or v10.16.0. Older Node versions will fall back to gzip.
fix Upgrade Node.js to v11.7.0+ or v10.16.0+ for brotli support.
deprecated The option 'level' with value -1 (default) is equivalent to zlib.Z_DEFAULT_COMPRESSION (level 6). Use explicit level for clarity.
fix Set level explicitly: compression({ level: 6 }).
gotcha Compression is skipped for responses with Cache-Control: no-transform. Be aware if you're using CDNs or reverse proxies.
fix Remove no-transform directive if compression is desired.
gotcha The middleware compresses only if the request's Accept-Encoding header includes the encoding. Client must support it.
fix Ensure client sends Accept-Encoding header.
npm install compression-with-brotli
yarn add compression-with-brotli
pnpm add compression-with-brotli

Basic Express server with compression middleware. Handles a 100KB string response that will be compressed.

const express = require('express');
const compression = require('compression');

const app = express();

// Enable compression for all responses
app.use(compression());

// Route that returns a large response
app.get('/large', (req, res) => {
  const largeString = 'x'.repeat(1024 * 100); // 100KB string
  res.send(largeString);
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});