compression
HTTP response compression middleware for Express — gzip/deflate responses to reduce bandwidth and improve load times.
compression
ExpressHTTP response compression middleware for Express — gzip/deflate responses to reduce bandwidth and improve load times.
Fit
Bundle (gzip)
29.5 kB
177.9 kB raw
Install size includes transitive dependencies. Bundle size is gzipped browser payload.
Freshness
The Problem
Serving large JSON API responses and static assets uncompressed wastes bandwidth and slows down clients. Configuring gzip correctly at the application level (vs. a reverse proxy) requires understanding content negotiation and threshold tuning.
What It Does
The compression middleware compresses responses when the client sends an Accept-Encoding: gzip header and the response exceeds the threshold size. It negotiates between gzip and deflate, skips binary formats (images, video), and adds the appropriate Content-Encoding header.
Installation
npm install compression
npm install -D @types/compressionUsage Example
import express from 'express';
import compression from 'compression';
const app = express();
// Apply to all routes
app.use(compression({
threshold: 1024, // only compress responses > 1KB
filter: (req, res) => {
// Skip compression for already-compressed formats
if (req.headers['x-no-compression']) return false;
return compression.filter(req, res);
},
}));
app.get('/data', (req, res) => {
res.json({ users: largeUsersArray }); // automatically gzipped
});Related packages
Node.js body parsing middleware — populate `req.body` from JSON, urlencoded, text, and raw payloads.
cookie-parserExpressCookie parsing middleware for Express — parse Cookie headers into `req.cookies` and support signed cookies for tamper detection.
corsExpressCORS middleware for Express — configure cross-origin resource sharing with a single line of code.
express-async-errorsExpressSimplify Express error handling by automatically passing thrown errors to `next()`.
express-fileuploadExpressSimple Express middleware for handling `multipart/form-data` file uploads, built on Busboy.