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 install compression
yarn add compression
pnpm add compression
Import
import compression from 'compression';
Quick Example
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
| Package | compression |
| Category | HTTP |
| Weekly Downloads | 5M+ |
| License | MIT |
| Install | npm install compression |
Related Packages
Express is the most widely used web application framework for Node.js, providing a minimal and flexi…
Helmet helps secure Express.js applications by setting various HTTP response headers that protect ag…
CORS (Cross-Origin Resource Sharing) is an Express/Connect middleware that enables cross-origin requ…
Body-parser is a Node.js body parsing middleware that extracts the body portion of incoming HTTP req…
Browse npm Packages by Category
Explore our reference of 200 popular npm packages with install commands, examples, and quick-start guides.