Node.js Compression Middleware with Brotli Support

1.0.3 · active · verified Wed Apr 22

compression-next is a Node.js middleware designed for compressing HTTP responses, offering support for `deflate`, `gzip`, and `brotli` encodings. Currently at version 1.0.3, this package originated as a pragmatic fork to provide immediate `brotli` compression functionality, addressing a long-standing feature request within the `expressjs/compression` project. Its release cadence is reactive, likely responding to updates in Node.js's native `zlib` module or the upstream `expressjs/compression` project. A primary differentiator is its readily available `brotli` support, a feature not present in the mainstream `expressjs/compression` at the time of its inception. Developers using this library should be aware of its temporary nature, with the expectation to transition back to the core `expressjs/compression` once `brotli` is officially integrated there. It integrates seamlessly with popular Node.js web frameworks like Express.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to integrate `compression-next` with an Express application, applying compression to HTTP responses. It shows basic usage with options like compression level and a custom filter.

import express from 'express';
import compression from 'compression-next';
import { Z_BEST_COMPRESSION, constants } from 'zlib'; // Import zlib constants for options

const app = express();
const port = 3000;

// Apply compression middleware
app.use(compression({
  // For gzip/deflate, use 'level' option
  level: Z_BEST_COMPRESSION, // Example: apply best gzip/deflate compression
  // For brotli specific parameters, use 'params'
  // params: {
  //   [constants.BROTLI_PARAM_MODE]: constants.BROTLI_MODE_TEXT,
  //   [constants.BROTLI_PARAM_QUALITY]: constants.BROTLI_MAX_QUALITY
  // },
  filter: (req, res) => {
    if (req.headers['x-no-compression']) {
      // Example: Do not compress responses with a specific header
      return false;
    }
    // Fallback to the default filter function (which uses 'compressible' module)
    return compression.filter(req, res);
  }
}));

// Route for a simple text response
app.get('/', (req, res) => {
  res.send('Hello World! This response should be compressed.');
});

// Route for a larger JSON response to better demonstrate compression effect
app.get('/data', (req, res) => {
  const largeData = Array(500).fill({ id: Math.random(), value: 'some repetitive text here for good compression effect and larger payload size to showcase middleware functionality.' });
  res.json(largeData);
});

app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
  console.log('Test with curl -H "Accept-Encoding: gzip, deflate, br" http://localhost:3000/data');
  console.log('And without: curl http://localhost:3000/data');
});

view raw JSON →