Brotli Compression
What is Brotli Compression?
Brotli (br) is a modern lossless compression algorithm developed by Google, offering 20-26% better compression ratios compared to gzip. Key technical specifications:
- Compression Levels: 11 levels (0-11) with intelligent defaults
- Supported Content Types: Text-based formats (HTML, CSS, JS, SVG, JSON)
- Header Support:
Content-Encoding: br
- Browser Support: 96% global coverage (Chrome 50+, Firefox 44+, Edge 15+)
Implementation Guide
Web Server Configuration
Nginx:
brotli on;
brotli_comp_level 6;
brotli_types text/plain text/css application/json application/javascript;
Apache (mod_brotli):
<IfModule mod_brotli.c>
AddOutputFilterByType BROTLI_COMPRESS text/css
BrotliCompressionQuality 11
</IfModule>
Next.js Configuration
// next.config.js
module.exports = {
compress: true, // Enables built-in Brotli in Next.js 10+
};
Client-Side Detection
// Check Brotli support
const supportsBrotli = "Br" in new Headers().getAcceptEncoding();
Performance Benchmarks
File Type | Original | Gzip | Brotli | Δ vs Gzip |
---|---|---|---|---|
app.js (2.1MB) | 2100 KB | 412 KB | 321 KB | -22% |
styles.css (150KB) | 150 KB | 28 KB | 21 KB | -25% |
HTML document | 18 KB | 3.2 KB | 2.5 KB | -22% |
CDN Integration
Cloud services configuration examples:
AWS CloudFront:
- Create cache policy with
Accept-Encoding
header - Add Brotli to origin request policy
- Set compression format to Br in behaviors
Cloudflare:
Brotli enabled by default for:
- All text-based content
- Clients supporting br encoding
Advanced Optimization
- Pre-compression:
# Generate .br files during build
brotli -k -q 11 build/**/*.{html,css,js}
- Content Negotiation:
map $http_accept_encoding $compression {
default gzip;
"br" br;
"gzip" gzip;
}
- Cache Control:
Cache-Control: public, max-age=31536000, immutable
Vary: Accept-Encoding
Troubleshooting
Common issues and solutions:
- Invalid Headers: Ensure
Vary: Accept-Encoding
present - Mixed Content: Prefer HTTPS for Brotli delivery
- Compression Level Tuning:
- Level 4: Fastest compression (dynamic content)
- Level 11: Maximum compression (static assets)