🌐
HTTP5M+/wkMIT

compression

Compression is a Node.js middleware that compresses HTTP response bodies using gzip, deflate, or Brotli encoding before sending them to the client. Compressing

Installation

npm
npm install compression
yarn
yarn add compression
pnpm
pnpm add compression

Import

ESM
import compression from 'compression';

Quick Example

usage
import express from 'express';
import compression from 'compression';

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

app.get('/data', (req, res) => {
  res.json({ large: 'response data' });
});

About compression

Compression is a Node.js middleware that compresses HTTP response bodies using gzip, deflate, or Brotli encoding before sending them to the client. Compressing responses can dramatically reduce the amount of data transferred over the network, typically achieving 60-80% size reduction for text-based content like HTML, CSS, JavaScript, and JSON. The middleware automatically negotiates the best compression algorithm based on the client's Accept-Encoding header, preferring Brotli when supported as it offers better compression ratios than gzip. Compression can be configured with a threshold option that skips compression for small responses where the overhead would outweigh the benefit, a filter function to selectively compress based on request or response properties, and compression level settings to balance CPU usage against compression ratio. The middleware is designed for Express and Connect frameworks and integrates seamlessly into the middleware chain. While reverse proxies like Nginx or CDNs often handle compression in production, the compression middleware is valuable during development, for direct Node.js deployments, and as a fallback when infrastructure-level compression is not available.

Quick Facts

Packagecompression
CategoryHTTP
Weekly Downloads5M+
LicenseMIT
Installnpm install compression

Related Packages

Browse npm Packages by Category

Explore our reference of 200 popular npm packages with install commands, examples, and quick-start guides.