Node.js HTTP Compression Middleware

1.8.1 · active · verified Wed Apr 22

The `compression` package provides middleware for Node.js, primarily designed for Express applications, to automatically compress HTTP responses. It supports common compression algorithms including gzip, deflate, and brotli. The current stable version is 1.8.1. Releases occur on an as-needed basis, typically for dependency updates, minor bug fixes, or to incorporate newer Node.js features, indicating an active maintenance status rather than rapid feature development. Key differentiators include its seamless integration into the Express middleware stack, configurable compression options (like level, chunk size, and memory level), and a flexible `filter` function to control which responses are compressed. It leverages Node.js's built-in `zlib` module for compression capabilities and ensures compliance with HTTP standards by respecting `Cache-Control: no-transform` directives.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up `compression` middleware in an Express application, including custom filtering and Brotli-specific options, to serve compressed HTML content.

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

const app = express();

// Use the compression middleware
app.use(compression({
  level: 6, // Default compression level
  filter: (req, res) => {
    if (req.headers['x-no-compression']) {
      // don't compress responses with this header
      return false;
    }
    // fallback to standard filter function
    return compression.filter(req, res);
  },
  brotli: { // Brotli specific options, requires Node.js >= 10.16.0 or >= 11.7.0
    params: {
      [compression.constants.BROTLI_PARAM_QUALITY]: 4
    }
  }
}));

app.get('/', (req, res) => {
  res.type('text/html');
  res.send(`
    <!DOCTYPE html>
    <html>
    <head><title>Compressed Page</title></head>
    <body>
      <h1>Hello, Compressed World!</h1>
      <p>This is a lengthy paragraph to ensure the response body is large enough to benefit from compression. The compression middleware will automatically compress this content if the client supports it.</p>
      <p>Current time: ${new Date().toISOString()}</p>
      <p>You can inspect the 'Content-Encoding' header in your browser's developer tools or by using 'curl -H "Accept-Encoding: gzip" http://localhost:3000 -v' to confirm compression.</p>
    </body>
    </html>
  `);
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log('Try visiting in your browser or using curl -H "Accept-Encoding: gzip" http://localhost:3000 -v');
});

view raw JSON →