compression-middleware Overview
The compression middleware automatically compresses HTTP response bodies before sending them to the client. This reduces the amount of data transferred over the network, making your application faster -- especially for users on slow connections.
What is HTTP Compression?
When a browser requests a page, the server sends back HTML, CSS, JavaScript, and JSON as plain text. HTTP compression shrinks that text before sending it, and the browser decompresses it on arrival. This happens transparently -- neither your application code nor the end user needs to do anything special.
Think of it like zipping a file before emailing it. The file is smaller during transit, but the recipient gets the original contents after unzipping.
How It Works
- The browser sends an
Accept-Encodingheader listing the compression formats it supports (e.g.,gzip, br, deflate). - The server picks the best format and compresses the response body.
- The server sets a
Content-Encodingheader so the browser knows how to decompress it.
This negotiation happens on every request, so the server always picks a format the browser understands.
Supported Encodings
The middleware supports three compression algorithms, listed from most to least efficient:
| Encoding | Name | Compression Ratio | Speed | Browser Support |
|---|---|---|---|---|
br | Brotli | Best | Slower to compress | All modern browsers |
gzip | Gzip | Good | Fast | Universal |
deflate | Deflate | Good | Fast | Universal |
By default, the middleware prefers Brotli when the client supports it, falling back to gzip, then deflate.
When to Use Compression
Use compression when:
- Your responses contain text-based content (HTML, CSS, JavaScript, JSON, SVG).
- You want to reduce bandwidth usage and improve load times.
- You are not behind a reverse proxy (like Nginx or Cloudflare) that already handles compression.
Skip compression when:
- A reverse proxy or CDN already compresses responses for you (double compression wastes CPU).
- Your responses are already compressed (images, videos, ZIP files).
- Responses are very small (the overhead of compression headers can outweigh the savings).
Quick Example
import { createRouter } from 'remix/fetch-router'
import { compression } from 'remix/compression-middleware'
let router = createRouter({
middleware: [
compression(),
],
})
router.get(routes.home, () => {
return new Response('<h1>Hello, world!</h1>', {
headers: { 'Content-Type': 'text/html' },
})
})The response body is automatically compressed if the client supports it and the body is larger than the threshold (1024 bytes by default).
Next Steps
- Tutorial: Add Compression to Your Server -- A hands-on guide to setting up and verifying compression.
- API Reference -- Complete documentation of options and behavior.