Koa Compress Middleware

5.2.1 · active · verified Wed Apr 22

`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.

Common errors

Warnings

Install

Imports

Quickstart

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`.

import Koa from 'koa';
import compress from 'koa-compress';
import { constants as zlibConstants } from 'zlib'; // Required for zlib options

const app = new Koa();

// Example of how to manually control compression for specific routes or conditions
app.use(async (ctx, next) => {
  // Forcing compression (bypasses filter)
  // ctx.compress = true;
  // Disabling compression
  // ctx.compress = false;
  // Overriding options for a specific response
  // ctx.compress = { threshold: 10, gzip: { level: 9 } };
  await next();
});

app.use(
  compress({
    // Predicate function to determine if a response should be compressed
    filter(content_type) {
      return /text|json|javascript/i.test(content_type || '');
    },
    // Minimum response size in bytes to trigger compression
    threshold: 2048,
    gzip: {
      flush: zlibConstants.Z_SYNC_FLUSH, // Use constants from Node's zlib
      level: 6 // Default gzip compression level
    },
    deflate: {
      flush: zlibConstants.Z_SYNC_FLUSH
    },
    // Brotli (br) is enabled by default. Set to false to disable or provide options.
    // br: false,
    // br: { quality: 4 }, // Example: Lower brotli quality for faster compression
    // Zstandard (zstd) is automatically enabled if supported by Node.js runtime.
    // zstd: { level: 1 }, // Example: Zstd compression level
    defaultEncoding: 'identity' // When client sends no Accept-Encoding header
  }),
);

// A route that serves a compressible body
app.use((ctx) => {
  ctx.type = 'text/plain';
  // Ensure body size exceeds the threshold for compression to apply
  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.'
    .repeat(50); 
});

const port = 3000;
app.listen(port, () => {
  console.log(`Koa server running on http://localhost:${port}`);
  console.log('Test compression: curl -H "Accept-Encoding: gzip" -I http://localhost:3000');
});

view raw JSON →