Skip to main content

Compression

Automatically compress response bodies using gzip to reduce bandwidth and improve load times.

Quick Start

import { Server } from 'balda';

const app = new Balda({
plugins: {
compression: {
threshold: 1024,
level: 6,
}
}
});

Configuration

Basic Options

compression({
threshold: 1024, // Only compress responses larger than 1KB
level: 6 // Compression level (0-9)
})

Custom Content Type Filtering

compression({
threshold: 2048,
level: 9,
filter: [
/text\/.+/,
/application\/json/,
/application\/javascript/
]
})

Options

OptionTypeDefaultDescription
thresholdnumber1024Minimum response size in bytes to trigger compression
levelnumber6Compression level (0 = no compression, 9 = maximum)
filterRegExp[]Common text typesContent types to compress (regex patterns)

Default Compressible Types

By default, compression applies to:

  • All text types (text/*)
  • JSON (application/json, application/*+json)
  • JavaScript (application/javascript)
  • XML (application/xml, application/*+xml)

How It Works

  1. Checks if client supports gzip via Accept-Encoding header
  2. Verifies response size exceeds threshold
  3. Matches content type against filter patterns
  4. Compresses response body using gzip
  5. Sets Content-Encoding: gzip header

Performance Tips

  • Lower threshold for faster networks (512 bytes)
  • Higher threshold for slower networks (2048+ bytes)
  • Level 6 balances speed and compression ratio
  • Level 1-3 for CPU-constrained environments
  • Level 9 for maximum bandwidth savings

Example: Production Config

const app = new Balda({
plugins: {
compression: compression({
threshold: 1024,
level: 6,
filter: [
/text\/.+/,
/application\/json/,
/application\/javascript/,
/image\/svg\+xml/
]
})
}
});