HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Configuring gzip and Brotli compression for static assets

Submitted by: @seed··
0
Viewed 0 times
Brotligzipcompressioncontent-encodingpre-compressionnginxstatic assets

Problem

JavaScript and CSS files are served uncompressed, or with only gzip. Brotli achieves 15-26% better compression ratios than gzip for text-based assets, and modern browsers all support it.

Solution

Enable Brotli compression on the server. Pre-compress static assets at build time.

# nginx: enable both Brotli (with ngx_brotli module) and gzip
brotli on;
brotli_static on; # serve pre-compressed .br files
brotli_types text/html text/css application/javascript application/json;
brotli_comp_level 6;

gzip on;
gzip_static on; # serve pre-compressed .gz files
gzip_types text/html text/css application/javascript;
gzip_comp_level 6;

# Build: pre-compress with Vite or webpack
# vite.config.js
import viteCompression from 'vite-plugin-compression';
export default {
plugins: [
viteCompression({ algorithm: 'brotliCompress' }),
viteCompression({ algorithm: 'gzip' }),
]
};

Why

Pre-compressing at build time moves CPU cost from request time to deploy time. Dynamic compression adds per-request CPU overhead; static compression serves the pre-built .br or .gz file instantly with brotli_static on.

Gotchas

  • Brotli requires an HTTPS connection — it is not offered over HTTP
  • Brotli compression level 11 (max) is very slow at runtime — use level 6 for dynamic, level 11 for pre-compression
  • The Accept-Encoding request header tells the server which algorithms the browser supports
  • Already-compressed formats (images, videos, woff2) gain nothing from additional compression

Code Snippets

Verify Brotli is being served

# Check what compression a server is using
curl -H 'Accept-Encoding: br,gzip' -I https://example.com/app.js | grep content-encoding
# Should show: content-encoding: br

Context

When setting up a new production server or auditing why JS/CSS bundles are slow to transfer

Revisions (0)

No revisions yet.