compression-middleware
The compression middleware compresses HTTP response bodies to reduce transfer size. It negotiates the best encoding with the client using the Accept-Encoding header and supports gzip, brotli, and deflate.
Installation
The compression middleware is included with Remix. No additional installation is needed.
Import
import { compression } from 'remix/compression-middleware'API
compression(options?)
Returns a middleware function that compresses response bodies.
let router = createRouter({
middleware: [
compression(),
],
})Options
| Option | Type | Default | Description |
|---|---|---|---|
threshold | number | 1024 | Minimum response size in bytes before compression is applied. Responses smaller than this are sent uncompressed. |
encodings | string[] | ['br', 'gzip', 'deflate'] | Ordered list of encodings to support. The first encoding that the client accepts is used. |
Behavior
The middleware:
- Reads the
Accept-Encodingheader from the request. - Selects the best supported encoding by comparing the client's preferences with the configured
encodingslist. - After the handler produces a response, compresses the body if:
- The response body is larger than
thresholdbytes. - The response does not already have a
Content-Encodingheader. - The
Content-Typeis compressible (text, JSON, HTML, SVG, JavaScript, CSS, etc.).
- The response body is larger than
- Sets the
Content-EncodingandVary: Accept-Encodingheaders on the compressed response.
The middleware respects Accept-Ranges headers. If a response includes Accept-Ranges: bytes (used for range requests, such as video streaming), compression is skipped to preserve byte-range semantics.
Examples
Basic Usage
import { createRouter } from 'remix/fetch-router'
import { compression } from 'remix/compression-middleware'
let router = createRouter({
middleware: [
compression(),
],
})Custom Threshold
Compress only responses larger than 2 KB:
compression({
threshold: 2048,
})Limit Encodings
Support only gzip (for environments where brotli is unavailable):
compression({
encodings: ['gzip', 'deflate'],
})Recommended Middleware Order
Place compression() early in the middleware chain so it wraps responses from all downstream middleware and handlers:
let router = createRouter({
middleware: [
logger(),
compression(),
staticFiles('./public'),
csrf(),
formData(),
],
})Related
- Middleware --- How middleware works in Remix.
- static-middleware --- Serving static files with compression.