{"id":17444,"library":"koa-compress","title":"Koa Compress Middleware","description":"`koa-compress` is a middleware for Koa.js applications that provides HTTP response compression. It is actively maintained, with the current stable version being 5.2.1, and demonstrates a consistent release cadence through regular patch and minor updates, such as `v5.2.0`, `v5.1.1`, and `v5.0.1`. The library automatically negotiates and applies various compression algorithms including `gzip`, `deflate`, `brotli` (br), and `zstandard` (zstd), adapting to client capabilities and server configuration. Key differentiators include its deep integration with the Koa context, allowing for granular control over compression via `ctx.compress` and `ctx.compress` as an options object. It offers flexible configuration for `filter` predicates, `threshold` for minimum compressible size, and algorithm-specific settings. Furthermore, it supports functional properties to dynamically adjust compression parameters based on response type, size, and the full Koa context, aiming to optimize network transfer sizes by offloading content encoding from application logic.","status":"active","version":"5.2.1","language":"javascript","source_language":"en","source_url":"https://github.com/koajs/compress","tags":["javascript","typescript"],"install":[{"cmd":"npm install koa-compress","lang":"bash","label":"npm"},{"cmd":"yarn add koa-compress","lang":"bash","label":"yarn"},{"cmd":"pnpm add koa-compress","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"While CommonJS `require` is shown in old examples, ESM `import` is the preferred modern approach for Koa applications, especially with TypeScript. This package exports a default function.","wrong":"const compress = require('koa-compress');","symbol":"compress","correct":"import compress from 'koa-compress';"},{"note":"For CommonJS environments, `require('koa-compress')` directly returns the middleware function, which is a default export. Do not attempt named imports with CommonJS.","wrong":"import { compress } from 'koa-compress';","symbol":"compress","correct":"const compress = require('koa-compress');"},{"note":"When using TypeScript, import `CompressOptions` to type the configuration object passed to the middleware.","symbol":"CompressOptions","correct":"import type { CompressOptions } from 'koa-compress';"},{"note":"For configuring `gzip` or `deflate` options like `flush`, you need to import `constants` directly from Node.js's built-in `zlib` module. Alias it for clarity.","wrong":"import * as zlib from 'zlib'; const flush = zlib.Z_SYNC_FLUSH;","symbol":"constants","correct":"import { constants as zlibConstants } from 'zlib';"}],"quickstart":{"code":"import Koa from 'koa';\nimport compress from 'koa-compress';\nimport { constants as zlibConstants } from 'zlib'; // Required for zlib options\n\nconst app = new Koa();\n\n// Example of how to manually control compression for specific routes or conditions\napp.use(async (ctx, next) => {\n  // Forcing compression (bypasses filter)\n  // ctx.compress = true;\n  // Disabling compression\n  // ctx.compress = false;\n  // Overriding options for a specific response\n  // ctx.compress = { threshold: 10, gzip: { level: 9 } };\n  await next();\n});\n\napp.use(\n  compress({\n    // Predicate function to determine if a response should be compressed\n    filter(content_type) {\n      return /text|json|javascript/i.test(content_type || '');\n    },\n    // Minimum response size in bytes to trigger compression\n    threshold: 2048,\n    gzip: {\n      flush: zlibConstants.Z_SYNC_FLUSH, // Use constants from Node's zlib\n      level: 6 // Default gzip compression level\n    },\n    deflate: {\n      flush: zlibConstants.Z_SYNC_FLUSH\n    },\n    // Brotli (br) is enabled by default. Set to false to disable or provide options.\n    // br: false,\n    // br: { quality: 4 }, // Example: Lower brotli quality for faster compression\n    // Zstandard (zstd) is automatically enabled if supported by Node.js runtime.\n    // zstd: { level: 1 }, // Example: Zstd compression level\n    defaultEncoding: 'identity' // When client sends no Accept-Encoding header\n  }),\n);\n\n// A route that serves a compressible body\napp.use((ctx) => {\n  ctx.type = 'text/plain';\n  // Ensure body size exceeds the threshold for compression to apply\n  ctx.body = 'This is a long string that will be compressed by koa-compress middleware if the client supports it and the size exceeds the threshold.'\n    .repeat(50); \n});\n\nconst port = 3000;\napp.listen(port, () => {\n  console.log(`Koa server running on http://localhost:${port}`);\n  console.log('Test compression: curl -H \"Accept-Encoding: gzip\" -I http://localhost:3000');\n});\n","lang":"typescript","description":"This quickstart demonstrates how to integrate `koa-compress` into a Koa application using ESM imports. It shows basic configuration, including `filter`, `threshold`, and algorithm-specific options using `zlib.constants`, and illustrates how to control compression manually via `ctx.compress`."},"warnings":[{"fix":"To restore the spec-compliant behavior, explicitly set `defaultEncoding: '*'` in the middleware options: `compress({ defaultEncoding: '*' })`.","message":"The default behavior for clients sending no `Accept-Encoding` header changed in `v5.0.0`. It now defaults to `'identity'` (no compression) instead of the HTTP spec-compliant `'*'` (any encoding). This can affect debugging tools like `curl` that often omit `Accept-Encoding` by default.","severity":"breaking","affected_versions":">=5.0.0"},{"fix":"Ensure your Node.js environment is `v10` or newer. Review the new options structure in the `koa-compress` documentation and update your configuration objects for `gzip`, `deflate`, and `br` accordingly. Brotli (br) support was also introduced in this version.","message":"Version 4.0.0 dropped support for Node.js versions below 10. Additionally, the way options were passed to compression functions (like `gzip`, `deflate`, `br`) changed significantly. Previous configurations may no longer be valid.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Upgrade your Node.js environment to a version that natively supports Zstandard (e.g., Node.js 22.15.0+ or 23.8.0+). The middleware automatically detects `zlib.createZstdCompress` at runtime; no code changes are needed if the runtime supports it.","message":"`zstandard` (zstd) compression is only supported natively in specific Node.js versions: `v22.15.0` (LTS) or `v23.8.0` (Current) and above. If your Node.js version is older, `zstd` compression will be silently skipped, even if configured.","severity":"gotcha","affected_versions":"<22.15.0 || <23.8.0 (for zstd only)"},{"fix":"Always import and use the `constants` object from Node.js's built-in `zlib` module. For example, `import { constants as zlibConstants } from 'zlib';` and then use `flush: zlibConstants.Z_SYNC_FLUSH`.","message":"When configuring `gzip` or `deflate` options, especially the `flush` property, direct numeric values or incorrect string literals can lead to errors. Node.js's `zlib` module expects specific `constants` for these settings.","severity":"gotcha","affected_versions":">=3.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Change your import statement to `import compress from 'koa-compress';` to use ES Module syntax. Ensure `import Koa from 'koa';` and other imports are also using ESM.","cause":"Attempting to use `require()` in an ES Module context (e.g., in a `.mjs` file or when `\"type\": \"module\"` is set in `package.json`).","error":"ReferenceError: require is not defined"},{"fix":"Ensure you import `constants` from Node.js's `zlib` module: `import { constants as zlibConstants } from 'zlib';`. Then, use these constants for flush options: `gzip: { flush: zlibConstants.Z_SYNC_FLUSH }`.","cause":"Incorrectly providing the `flush` option for `gzip` or `deflate` settings, often due to not importing `zlib.constants` or using an undefined value.","error":"ERR_INVALID_ARG_TYPE: The 'flush' argument must be one of type number. Received type undefined"},{"fix":"To disable an encoding like `br`, simply omit it from the `compress` options object or explicitly set `br: false`. If you intend to provide options, use an object: `br: { quality: 4 }`. The error message in this specific form indicates a misunderstanding or a type mismatch with expected configuration.","cause":"Passing a boolean value (`false`) to an encoding option (e.g., `br`) when the `options[encoding]` property expects an object for configuration or a function for dynamic options, and the middleware expects an explicit object for that type of configuration.","error":"Expected 'options.br' to be object or function but got false"},{"fix":"Review the `filter` function to ensure it correctly identifies the `ctx.type` for compression. Check the `threshold` value against `ctx.response.length` (or `ctx.body` size) to confirm the response is large enough. You can also temporarily force compression with `ctx.compress = true;` for debugging specific routes.","cause":"The response's MIME type does not match the `filter` predicate, or the response size is below the `threshold` configured in the middleware options.","error":"Response is not compressed (e.g., 'Content-Encoding' header missing) even when expected."}],"ecosystem":"npm","meta_description":null}