Skip to content

Web HTTP Compression

ItzNotABug edited this page May 3, 2024 · 1 revision

You can also use the standard HTTP Compression on the fly for faster content delivery!
Supported compressions are : Brotli, GZIP & Deflate

Default Behaviour

You can specify custom compression levels like this -

appExpress.compression(true, {br: 11, gzip: 6, deflate: 6})

Note: If the client sends multiple Accept-Encoding, Brotli is prioritized, then GZIP and Deflate at last.

Custom Compression

You can add a custom compression logic as well.

Example -

import zstd from '@mongodb-js/zstd';

express.compression({
  encodings: new Set(['zstd']),
  compress: async (buffer) => await zstd.compress(buffer, 9)}
});

Things to Consider

  1. Compression is applied to certain files only, they include -

    const contentTypePatterns = [
      /^text\/(html|css|plain|xml|x-component|javascript)$/i,
      /^application\/(x-javascript|javascript|json|manifest\+json|vnd\.api\+json|xml|xhtml\+xml|rss\+xml|atom\+xml|vnd\.ms-fontobject|x-font-ttf|x-font-opentype|x-font-truetype)$/i,
      /^image\/(svg\+xml|x-icon|vnd\.microsoft\.icon)$/i,
      /^font\/(ttf|eot|otf|opentype)$/i,
    ];
  2. If you use a Custom Compression, it is prioritized.

  3. If you use a Custom Compression and -

    • The Content-Type is not supported or
    • The Client doesn't include the encoding in the request that you are targeting

    then the default compression will be tried and applied.