How can I use "brotli" to compress files in Remix? #2698
Replies: 3 comments 5 replies
-
Compression of response is responsibility of the server not the app (Remix) so this will change depending on your server, in Express you can use the compression middleware, most of the other adapters use a server you don’t control and they most likely already support brotli like Vercel. |
Beta Was this translation helpful? Give feedback.
-
I ran into this issue while looking to compress text/html files. I have a Remix app with a CDN (cloudfront) behind it, however, compressing HTML is tricky because of streaming (I'm using Lambda FunctionURL so that I can use Remix's defer and stream content). Cloudfront requires the content length, but this may not always be known while streaming. One solution is to encode every chunk. Here's what I'm doing on my import zlib from 'node:zlib';
//...
const acceptEncoding = request.headers.get('accept-encoding') || '';
if (acceptEncoding.includes('br')) {
responseHeaders.set('Content-Encoding', 'br');
const brotli = zlib.createBrotliCompress();
pipe(brotli).pipe(body);
} else if (acceptEncoding.includes('gzip')) {
responseHeaders.set('Content-Encoding', 'gzip');
const gzip = zlib.createGzip();
pipe(gzip).pipe(body);
} else {
pipe(body);
}
resolve(
new Response(createReadableStreamFromReadable(body), {
headers: responseHeaders,
status: didError ? 500 : responseStatusCode,
}),
); |
Beta Was this translation helpful? Give feedback.
-
For anyone coming in, @clovis1122 answer is good, but cloudfront already has brotli compression on their side, which will make this NOT hit cache, recreating the request each time. so just use the cdn compression |
Beta Was this translation helpful? Give feedback.
-
Such as title
Beta Was this translation helpful? Give feedback.
All reactions