Skip to content

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

  1. The browser sends an Accept-Encoding header listing the compression formats it supports (e.g., gzip, br, deflate).
  2. The server picks the best format and compresses the response body.
  3. The server sets a Content-Encoding header 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:

EncodingNameCompression RatioSpeedBrowser Support
brBrotliBestSlower to compressAll modern browsers
gzipGzipGoodFastUniversal
deflateDeflateGoodFastUniversal

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

ts
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

Released under the MIT License.