@fastify/compress. It supports various compression algorithms like gzip, deflate, and brotli, and you can control compression per API.
Basic Structure
compress Settings
Enable/Disable
Type:boolean | FastifyCompressOptions
Key Options
global
Determines whether to automatically apply compression to all responses. Type:boolean
Default: true
true: Auto-compress all responses (default)false: Control per API with the@api({ compress })option
threshold
Minimum response size to start compression. Type:number (bytes)
Default: 1024 (1KB)
1024(1KB) - General web apps512(512B) - Compress small JSON responses too5120(5KB) - Compress only large responses
Compressing very small responses may have more overhead than benefit.
encodings
List of compression algorithms to support. Type:string[]
Default: ["gzip", "deflate"]
"gzip"- Most widely supported, fast compression"deflate"- Similar to gzip"br"(brotli) - High compression ratio, slower compression
Basic Examples
Recommended Settings
Including Brotli
Auto Compression (All Responses)
Per-API Compression Control
If you setglobal: false, you can control compression per API with the compress option of the @api() decorator.
Practical Examples
Standard Web API
CDN Optimization
Development vs Production
High Compression Settings
Additional Options
gzip Level
Z_BEST_SPEED(1) - Fast compressionZ_DEFAULT_COMPRESSION(6) - Default (recommended)Z_BEST_COMPRESSION(9) - Maximum compression
Compress Specific Content-Types Only
Compression Exclusion
Verifying Compression
How to verify if responses are compressed:Browser Developer Tools
- Open Network tab
- Check response headers:
- Check Size:
curl Test
Performance Impact
Compression Trade-offs
Benefits:- Bandwidth savings (50-80% reduction)
- Faster transfer time (especially on slow networks)
- CDN cost savings
- Increased CPU usage
- Increased Time To First Byte (TTFB)
- Increased memory usage
Recommendations
Should compress:- JSON responses (API)
- HTML, CSS, JavaScript
- SVG, XML
- Text files
- Images (JPEG, PNG, WebP) - Already compressed
- Videos (MP4, WebM) - Already compressed
- Compressed files (ZIP, GZ) - Already compressed
- Very small responses (< 1KB)
Cautions
1. Already Compressed Files
2. CPU Usage
3. threshold Setting
Next Steps
After completing response compression settings:- compress decorator - Per-API compression control
- cache-control - Using cache with compression
- performance - Performance optimization