Precompressing Vite assets with Brotli and Gzip
Emit .br and .gz files during a Vite build, configure Nginx static compression, and verify content negotiation, fallback, and cache behavior.
Instead of compressing a JavaScript file on every request, I can generate its Brotli and Gzip variants with the Vite build. Nginx can serve a matching variant from disk and keep the original file available for clients that request an identity response.
Choose when to spend CPU on compression
| Concern | Compression on request | Compression at build time |
|---|---|---|
| When work happens | During a request or cache fill | Once per versioned file during the build |
| Server load | Encoding can add CPU and delay | Serving still uses CPU and I/O but skips online encoding |
| Compression setting | Often balanced against request latency | Can use a slower level if the build budget allows it |
| Coverage | Suitable for content generated at request time | Suitable for static, reproducible assets |
Text assets often compress well. Already compressed images generally benefit less. Brotli level 11 increases build cost, so I measure whether it meaningfully reduces transfer bytes before applying that setting broadly. If a CDN already compresses or caches variants, measure the path the user actually hits.
Serve a variant for the original URL
flowchart TD
Client["Browser (Accept-Encoding: br, gzip)"] --> Nginx["Nginx web server"]
subgraph Storage["dist/assets (Vite output)"]
Raw["index.js (112.4 kB)"]
Gz["index.js.gz (29.1 kB)"]
Br["index.js.br (24.8 kB)"]
end
Nginx -->|"Check Brotli support"| CheckBr{"index.js.br available?"}
CheckBr -->|"Yes (brotli_static)"| ServeBr["Content-Encoding: br (24.8 kB)"]
CheckBr -->|"No"| CheckGz{"index.js.gz available?"}
CheckGz -->|"Yes (gzip_static)"| ServeGz["Content-Encoding: gzip (29.1 kB)"]
CheckGz -->|"No"| ServeRaw["No Content-Encoding (112.4 kB)"]
ServeBr --> Client
ServeGz --> Client
ServeRaw --> Client
The browser requests index.js and sends Accept-Encoding. The static modules can select the compressed sibling when it exists and the request accepts it. The public URL and media type remain those of the JavaScript file. Content-Encoding tells the browser what it received.
Generate both compressed variants
1
2
# Install the compression plugin
pnpm add -D vite-plugin-compression
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import compression from 'vite-plugin-compression';
export default defineConfig({
plugins: [
react(),
// 1. Generate Gzip files (.gz)
compression({
algorithm: 'gzip',
ext: '.gz',
threshold: 1024, // Compress files at least 1 kB
deleteOriginFile: false, // Keep the uncompressed fallback
verbose: true, // Log compression results
}),
// 2. Generate Brotli files (.br)
compression({
algorithm: 'brotliCompress',
ext: '.br',
threshold: 1024,
deleteOriginFile: false,
verbose: true,
}),
],
build: {
reportCompressedSize: false, // Avoid the separate built-in size report
},
});
threshold: 1024 ignores very small files where the compression wrapper may outweigh savings. deleteOriginFile: false keeps the original available for clients and tooling that need a plain response. Store and deploy the original and its variants together so each copy matches the same asset version.
Enable Nginx static compression
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# /etc/nginx/conf.d/default.conf
server {
listen 80;
server_name portal.example.com;
root /usr/share/nginx/html;
index index.html;
# 1. Enable the precompressed static modules
gzip_static on; # Use the .gz sibling when appropriate
brotli_static on; # Use the .br sibling (requires ngx_brotli)
# 2. Cache settings and response headers
location ~* \.(?:css|js|mjs|svg|woff2)$ {
expires 1y;
add_header Cache-Control "public, max-age=31536000, immutable";
add_header Vary "Accept-Encoding";
access_log off;
}
location / {
try_files $uri $uri/ /index.html;
}
}
gzip_static and brotli_static require the corresponding modules in the server build. Check the installed package or container image. In particular, Brotli static support is not present in every Nginx distribution. Run an Nginx configuration check before reloading.
Use an immutable one-year cache policy only on content-hashed assets. Scope the sample’s static cache rule to the hashed output directory if the deployment also serves stable paths that change in place.
Ensure responses and caches vary on Accept-Encoding. Otherwise an intermediary could serve a Brotli variant to a client that never requested it. Check the deployed cache behavior because a proxy or CDN can modify headers and encoding.
Compare the generated variants
Figure 1. The build records individual compression outcomes for the entry and vendor assets.
| Asset | Original | Gzip | Brotli |
|---|---|---|---|
vendor-core-A1.js | 284.10 kB | 78.20 kB (72.4% smaller) | 64.50 kB (77.3% smaller) |
index-D7a2.js | 112.40 kB | 29.10 kB (74.1% smaller) | 24.80 kB (77.9% smaller) |
Brotli saves several more percentage points than Gzip for these two files. The precise difference depends on the source bytes and compressor settings.
Test negotiated responses at the serving edge
Figure 2. The example Brotli response has a Content-Length of 25,395 bytes.
Request the same asset with Accept-Encoding: br, gzip, with just gzip, and with identity. Inspect Content-Encoding, Vary, and Content-Length. The identity response must still be usable and retain the original media type. Repeat against the CDN if the deployed path uses one.
This reduces transfer cost for the files that remain after bundle analysis. I track the measured size at both stages so compression does not hide a growing JavaScript payload.