{"id":16975,"library":"compression","title":"Node.js HTTP Compression Middleware","description":"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.","status":"active","version":"1.8.1","language":"javascript","source_language":"en","source_url":"https://github.com/expressjs/compression","tags":["javascript","compression","gzip","deflate","middleware","express","brotli","http","stream"],"install":[{"cmd":"npm install compression","lang":"bash","label":"npm"},{"cmd":"yarn add compression","lang":"bash","label":"yarn"},{"cmd":"pnpm add compression","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Used by the default `filter` function to determine if a response's Content-Type is suitable for compression.","package":"compressible","optional":false},{"reason":"Used internally for byte-related operations.","package":"bytes","optional":false}],"imports":[{"note":"The `compression` module exports a default function. Even if using ES modules, it's typically imported as a default.","wrong":"import { compression } from 'compression';","symbol":"compression","correct":"import compression from 'compression';"},{"note":"This is the standard CommonJS import pattern shown in the documentation and prevalent in older Node.js/Express applications.","symbol":"compression","correct":"const compression = require('compression');"},{"note":"When using TypeScript, type definitions are often provided for the configuration options. This is a type-only import.","wrong":"import { CompressionOptions } from 'compression';","symbol":"CompressionOptions","correct":"import type { CompressionOptions } from 'compression';"}],"quickstart":{"code":"import express from 'express';\nimport compression from 'compression';\n\nconst app = express();\n\n// Use the compression middleware\napp.use(compression({\n  level: 6, // Default compression level\n  filter: (req, res) => {\n    if (req.headers['x-no-compression']) {\n      // don't compress responses with this header\n      return false;\n    }\n    // fallback to standard filter function\n    return compression.filter(req, res);\n  },\n  brotli: { // Brotli specific options, requires Node.js >= 10.16.0 or >= 11.7.0\n    params: {\n      [compression.constants.BROTLI_PARAM_QUALITY]: 4\n    }\n  }\n}));\n\napp.get('/', (req, res) => {\n  res.type('text/html');\n  res.send(`\n    <!DOCTYPE html>\n    <html>\n    <head><title>Compressed Page</title></head>\n    <body>\n      <h1>Hello, Compressed World!</h1>\n      <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>\n      <p>Current time: ${new Date().toISOString()}</p>\n      <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>\n    </body>\n    </html>\n  `);\n});\n\nconst PORT = 3000;\napp.listen(PORT, () => {\n  console.log(`Server running on http://localhost:${PORT}`);\n  console.log('Try visiting in your browser or using curl -H \"Accept-Encoding: gzip\" http://localhost:3000 -v');\n});\n","lang":"typescript","description":"This quickstart demonstrates setting up `compression` middleware in an Express application, including custom filtering and Brotli-specific options, to serve compressed HTML content."},"warnings":[{"fix":"Ensure your Node.js environment meets the minimum version requirements for Brotli support, or configure the middleware to only use gzip/deflate on older environments.","message":"Brotli compression (encoding 'br') is only supported in Node.js versions v11.7.0 and later, or v10.16.0 and later. Attempting to use Brotli options on older Node.js versions will result in an unsupported encoding error or silent failure to compress.","severity":"gotcha","affected_versions":"<10.16.0 || (>=10.0.0 <10.16.0) || (>=11.0.0 <11.7.0)"},{"fix":"If you desire compression for responses with `Cache-Control: no-transform`, you must manually remove or modify that header before the `compression` middleware is applied. However, consider the implications for caching and proxies.","message":"The middleware will explicitly skip compression if the `Cache-Control` response header contains the `no-transform` directive. This is standard HTTP behavior to prevent intermediaries from altering content, but can sometimes lead to unexpected uncompressed responses if not intended.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Implement a custom `filter` function in the `compression` options that explicitly checks for your desired `Content-Type` headers alongside or instead of the default logic.","message":"The default `filter` function relies on the `compressible` package to determine if a `Content-Type` is suitable for compression. If you're serving custom or unusual `Content-Type` headers that you wish to compress, you may need to provide a custom `filter` function.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For wider compatibility across Node.js versions, avoid direct references to `zlib.constants` for older Node.js versions if possible, or provide fallback values. However, `compression` typically handles this gracefully internally.","message":"While not a direct breaking change from `compression` itself, Node.js `zlib` API constants used for options (like `Z_DEFAULT_COMPRESSION`) are available directly on `zlib` module from Node.js v11.0.0+. For older Node.js versions, they might be nested or less consistently exposed, potentially affecting options configuration.","severity":"breaking","affected_versions":"<11.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Upgrade your Node.js version to at least v10.16.0 or v11.7.0, or remove the `brotli` options from the `compression` middleware configuration.","cause":"Attempting to use Brotli compression (`br`) in a Node.js environment that does not support it (versions older than v10.16.0 or v11.7.0).","error":"Error: Brotli: Unsupported encoding"},{"fix":"Ensure that `app` is a valid Express application instance (e.g., `const app = express();`) or an Express router, and that `app.use()` is called correctly with the middleware.","cause":"The `compression` middleware is being applied to an object that is not an Express application instance or router, or `express()` was not correctly called.","error":"TypeError: app.use is not a function"},{"fix":"Review the order of your middleware and ensure that all header-modifying operations occur before the `compression` middleware and before any part of the response body is flushed.","cause":"This warning can occur if another middleware or route handler attempts to modify response headers after `compression` (or another middleware) has already sent headers to the client, typically because the response body has started streaming.","error":"Warning: Can't set headers after they are sent."}],"ecosystem":"npm","meta_description":null}