Features
Docs
CLI
Benchmarks
Examples

© 2024 MoroJs

Response Compression

Compress HTTP responses with gzip, deflate, or brotli to reduce bandwidth usage and improve application performance.

Compression That Just Works

Enable compression with one line.
gzip, deflate, or brotli. Automatic detection. 60-80% bandwidth reduction.

It's This Simple

Enable compression with one line

typescript

1import { compression } from '@morojs/moro';
2
3// Basic compression with defaults
4app.use(compression());
5
6// Compression is now enabled for all responses
7app.get('/api/data', (req, res) => {
8  return { data: largeDataset };
9});

Why Compression Matters

Without compression, you're wasting bandwidth, slowing down page loads, and increasing server costs. With MoroJS, you get 60-80% bandwidth reduction automatically.

Traditional compression setup requires manual configuration. We handle that automatically.

Without Compression

  • Wasted bandwidth (uncompressed responses)
  • Slower page loads
  • Higher server costs
  • Poor mobile experience

With MoroJS

  • 60-80% bandwidth reduction
  • Faster page loads
  • Lower server costs
  • Better mobile experience

Why It Makes Sense

Automatic

Detects client support and compresses automatically

Efficient

60-80% bandwidth reduction with minimal CPU overhead

Flexible

gzip, deflate, or brotli. Configurable per route.

How It Works

MoroJS provides built-in response compression middleware that automatically compresses responses using gzip, deflate, or brotli based on client support. The middleware detects the client's Accept-Encoding header and compresses responses larger than a configurable threshold.

Basic Compression

MoroJS provides built-in response compression middleware that automatically compresses responses using gzip, deflate, or brotli based on client support.

Basic Compression Setup

typescript

1import { compression } from '@morojs/moro';
2
3// Basic compression with defaults
4app.use(compression());
5
6// Compression is now enabled for all responses
7app.get('/api/data', (req, res) => {
8  return { data: largeDataset };
9});

Default Behavior

When compression is enabled, MoroJS automatically:

  • • Detects client compression support via Accept-Encoding header
  • • Compresses responses larger than 1KB by default
  • • Uses gzip for maximum compatibility
  • • Falls back to deflate if gzip is not supported
  • • Skips compression for already-compressed content

Advanced Configuration

Custom Compression Settings

typescript

1import { compression } from '@morojs/moro';
2
3// Advanced compression configuration
4app.use(compression({
5  level: 6, // Compression level (0-9), higher = better compression but slower
6  threshold: 1024, // Minimum size to compress (bytes)
7  filter: (req, res) => {
8    // Custom filter - don't compress if client requests no compression
9    if (req.headers['x-no-compression']) {
10      return false;
11    }
12    // Only compress JSON, text, JavaScript, and CSS
13    const contentType = res.getHeader('Content-Type') || '';
14    return /json|text|javascript|css/.test(contentType);
15  },
16  brotli: true, // Enable brotli for modern browsers
17  brotliOptions: {
18    params: {
19      [require('zlib').constants.BROTLI_PARAM_QUALITY]: 4
20    }
21  }
22}));

Compression Levels

  • 0-3 - Fast compression, larger files
  • 4-6 - Balanced (default: 6)
  • 7-9 - Maximum compression, slower

Compression Formats

  • gzip - Widest browser support
  • deflate - Fallback option
  • brotli - Best compression (modern browsers)

Per-Route Compression

Route-Specific Compression

typescript

1// Maximum compression for large data endpoints
2app.get('/api/large-data')
3  .compression({ level: 9 })
4  .handler((req, res) => {
5    return largeDataset; // Automatically compressed
6  });
7
8// Disable compression for specific routes
9app.get('/api/small-data')
10  .compression({ threshold: Infinity }) // Never compress
11  .handler((req, res) => {
12    return { message: 'Small response' };
13  });
14
15// Custom compression for streaming endpoints
16app.get('/api/stream')
17  .compression({ 
18    level: 4, // Faster compression for streaming
19    filter: (req, res) => {
20      // Only compress if client explicitly requests it
21      return req.headers['accept-encoding']?.includes('gzip');
22    }
23  })
24  .handler((req, res) => {
25    return streamData();
26  });

Best Practices

Do

  • • Enable compression for text-based content (JSON, HTML, CSS, JS)
  • • Use level 6 for balanced performance
  • • Set appropriate thresholds (1KB+) to avoid overhead
  • • Enable brotli for modern browsers
  • • Compress API responses with large payloads

Don't

  • • Compress already-compressed formats (images, videos)
  • • Use maximum compression for real-time endpoints
  • • Compress very small responses (< 1KB)
  • • Compress streaming responses without careful configuration
  • • Ignore client compression preferences

Production Configuration

typescript

1import { compression } from '@morojs/moro';
2
3// Production-optimized compression
4app.use(compression({
5  level: 6, // Balanced compression
6  threshold: 1024, // Only compress responses > 1KB
7  filter: (req, res) => {
8    const contentType = res.getHeader('Content-Type') || '';
9    
10    // Don't compress binary formats
11    if (/image|video|audio|application\/(zip|pdf|octet-stream)/.test(contentType)) {
12      return false;
13    }
14    
15    // Compress text-based content
16    return /json|text|javascript|css|html|xml/.test(contentType);
17  },
18  brotli: true, // Enable for modern browsers
19  brotliOptions: {
20    params: {
21      [require('zlib').constants.BROTLI_PARAM_QUALITY]: 4
22    }
23  }
24}));

Performance Impact

Compression Benefits

  • Bandwidth reduction: 60-80% for text-based content
  • Faster page loads: Reduced transfer time
  • Lower server costs: Less bandwidth usage
  • Better mobile experience: Faster on slow connections
  • CPU overhead: Minimal (~5-10ms per response)

Related Features