All Projects → fastify → Fastify Compress

fastify / Fastify Compress

Licence: mit
Fastify compression utils

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Fastify Compress

Turbobench
Compression Benchmark
Stars: ✭ 211 (+122.11%)
Mutual labels:  compression, gzip, brotli
EasyCompressor
⚡ A compression library that implements many compression algorithms such as LZ4, Zstd, LZMA, Snappy, Brotli, GZip, and Deflate. It helps you to improve performance by reducing Memory Usage and Network Traffic for caching.
Stars: ✭ 167 (+75.79%)
Mutual labels:  compression, gzip, brotli
gzipped
Replacement for golang http.FileServer which supports precompressed static assets.
Stars: ✭ 86 (-9.47%)
Mutual labels:  compression, gzip, brotli
pyrus-cramjam
Thin Python wrapper to de/compression algorithms in Rust - lightweight & no dependencies
Stars: ✭ 40 (-57.89%)
Mutual labels:  compression, gzip, brotli
Lizard
Lizard (formerly LZ5) is an efficient compressor with very fast decompression. It achieves compression ratio that is comparable to zip/zlib and zstd/brotli (at low and medium compression levels) at decompression speed of 1000 MB/s and faster.
Stars: ✭ 408 (+329.47%)
Mutual labels:  compression, brotli
Zoonavigator
Web-based ZooKeeper UI / editor / browser
Stars: ✭ 326 (+243.16%)
Mutual labels:  compression, gzip
Rust Brotli
Brotli compressor and decompressor written in rust that optionally avoids the stdlib
Stars: ✭ 504 (+430.53%)
Mutual labels:  compression, brotli
Django Compression Middleware
Django middleware to compress responses using several algorithms.
Stars: ✭ 23 (-75.79%)
Mutual labels:  gzip, brotli
Leanify
lightweight lossless file minifier/optimizer
Stars: ✭ 694 (+630.53%)
Mutual labels:  compression, gzip
Express Security
nodejs + express security and performance boilerplate.
Stars: ✭ 37 (-61.05%)
Mutual labels:  gzip, brotli
Aspnetcore Request Decompression
HTTP request decompression middleware for ASP.NET Core
Stars: ✭ 51 (-46.32%)
Mutual labels:  gzip, brotli
Compress
Collection of compression related Go packages.
Stars: ✭ 319 (+235.79%)
Mutual labels:  compression, brotli
Archiver
Easily create & extract archives, and compress & decompress files of various formats
Stars: ✭ 3,373 (+3450.53%)
Mutual labels:  gzip, brotli
Lzbench
lzbench is an in-memory benchmark of open-source LZ77/LZSS/LZMA compressors
Stars: ✭ 490 (+415.79%)
Mutual labels:  compression, brotli
lambda-smush-py
Gain additional code space via cheeky compression for Python AWS Lambda functions defined in-line to CloudFormation templates.
Stars: ✭ 17 (-82.11%)
Mutual labels:  compression, gzip
Peazip
Free Zip / Unzip software and Rar file extractor. Cross-platform file and archive manager. Features volume spanning, compression, authenticated encryption. Supports 7Z, 7-Zip sfx, ACE, ARJ, Brotli, BZ2, CAB, CHM, CPIO, DEB, GZ, ISO, JAR, LHA/LZH, NSIS, OOo, PAQ/LPAQ, PEA, QUAD, RAR, RPM, split, TAR, Z, ZIP, ZIPX, Zstandard.
Stars: ✭ 827 (+770.53%)
Mutual labels:  compression, brotli
Deno brotli
🗜 Brotli wasm module for deno
Stars: ✭ 40 (-57.89%)
Mutual labels:  compression, brotli
Genozip
Compressor for genomic files (FASTQ, SAM/BAM, VCF, FASTA, GVF, 23andMe...), up to 5x better than gzip and faster too
Stars: ✭ 53 (-44.21%)
Mutual labels:  compression, gzip
BrotliSharpLib
Full C# port of Brotli compression algorithm
Stars: ✭ 77 (-18.95%)
Mutual labels:  compression, brotli
Denoflate
WebAssembly powered Deflate/Gzip/Zlib compression for Deno, written in Rust
Stars: ✭ 80 (-15.79%)
Mutual labels:  compression, gzip

fastify-compress

Build Status js-standard-style

Adds compression utils to the Fastify reply object and a hook to decompress requests payloads. Supports gzip, deflate, and brotli.

Install

npm i fastify-compress

Usage - Compress replies

This plugin adds two functionalities to Fastify: a compress utility and a global compression hook.

Currently, the following encoding tokens are supported, using the first acceptable token in this order:

  1. br
  2. gzip
  3. deflate
  4. * (no preference — fastify-compress will use gzip)
  5. identity (no compression)

If an unsupported encoding is received or if the 'accept-encoding' header is missing, it will not compress the payload. If an unsupported encoding is received and you would like to return an error, provide an onUnsupportedEncoding option.

The plugin automatically decides if a payload should be compressed based on its content-type; if no content type is present, it will assume application/json.

Global hook

The global compression hook is enabled by default. To disable it, pass the option { global: false }:

fastify.register(
  require('fastify-compress'),
  { global: false }
)

Remember that thanks to the Fastify encapsulation model, you can set a global compression, but run it only in a subset of routes if you wrap them inside a plugin.

Per Route options

You can specify different options for compression per route by passing in the compress options on the route's configuration.

fastify.register(
  require('fastify-compress'),
  { global: false }
)

// only compress if the payload is above a certain size and use brotli
fastify.get('/custom-route', {
    config: {
      compress: {
        threshold: 128
        brotli: brotli
      }
    }
  }, (req, reply) => {
    // ...
  })

Note: Setting config.compress = false on any route will disable compression on the route even if global compression is enabled.

reply.compress

This plugin adds a compress method to reply that accepts a stream or a string, and compresses it based on the accept-encoding header. If a JS object is passed in, it will be stringified to JSON. Note that the compress method is configured with either the per route parameters if the route has a custom configuration or with the global parameters if the the route has no custom parameters but the plugin was defined as global.

const fs = require('fs')
const fastify = require('fastify')()

fastify.register(require('fastify-compress'), { global: false })

fastify.get('/', (req, reply) => {
  reply
    .type('text/plain')
    .compress(fs.createReadStream('./package.json'))
})

fastify.listen(3000, function (err) {
  if (err) throw err
  console.log(`server listening on ${fastify.server.address().port}`)
})

Compress Options

threshold

The minimum byte size for a response to be compressed. Defaults to 1024.

fastify.register(
  require('fastify-compress'),
  { threshold: 2048 }
)

customTypes

mime-db is used to determine if a content-type should be compressed. You can compress additional content types via regular expression.

fastify.register(
  require('fastify-compress'),
  { customTypes: /x-protobuf$/ }
)

onUnsupportedEncoding

When the encoding is not supported, a custom error response can be sent in place of the uncompressed payload by setting the onUnsupportedEncoding(encoding, request, reply) option to be a function that can modify the reply and return a string | Buffer | Stream | Error payload.

fastify.register(
  require('fastify-compress'),
  {
    onUnsupportedEncoding: (encoding, request, reply) => {
      reply.code(406)
      return 'We do not support the ' + encoding + ' encoding.'
    }
  }
)

Disable compression by header

You can selectively disable response compression by using the x-no-compression header in the request.

Inflate pre-compressed bodies for clients that do not support compression

Optional feature to inflate pre-compressed data if the client doesn't include one of the supported compression types in its accept-encoding header.

fastify.register(
  require('fastify-compress'),
  { inflateIfDeflated: true }
)

fastify.get('/file', (req, reply) =>
  // will inflate the file  on the way out for clients
  // that indicate they do not support compression
  reply.send(fs.createReadStream('./file.gz')))

Customize encoding priority

By default, fastify-compress prioritizes compression as described at the beginning of §Usage - Compress replies. You can change that by passing an array of compression tokens to the encodings option:

fastify.register(
  require('fastify-compress'),
  // Only support gzip and deflate, and prefer deflate to gzip
  { encodings: ['deflate', 'gzip'] }
)

brotliOptions and zlibOptions

You can tune compression by setting the brotliOptions and zlibOptions properties. These properties are passed directly to native node zlib methods, so they should match the corresponding class definitions.

  server.register(fastifyCompress, {
    brotliOptions: {
      params: {
        [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT, // useful for APIs that primarily return text
        [zlib.constants.BROTLI_PARAM_QUALITY]: 4, // default is 11, max is 11, min is 0
      },
    },
    zlibOptions: {
      level: 9, // default is 9, max is 9, min is 0
    }
  });

Usage - Decompress request payloads

This plugin adds a preParsing hook that decompress the request payload according to the content-encoding request header.

Currently, the following encoding tokens are supported:

  1. br
  2. gzip
  3. deflate

If an unsupported encoding or and invalid payload is received, the plugin will throw an error.

If the request header is missing, the plugin will not do anything and yield to the next hook.

Global hook

The global request decompression hook is enabled by default. To disable it, pass the option { global: false }:

fastify.register(
  require('fastify-compress'),
  { global: false }
)

Remember that thanks to the Fastify encapsulation model, you can set a global decompression, but run it only in a subset of routes if you wrap them inside a plugin.

Per Route options

You can specify different options for decompression per route by passing in the decompress options on the route's configuration.

fastify.register(
  require('fastify-compress'),
  { global: false }
)

// Always decompress using gzip
fastify.get('/custom-route', {
    config: {
      decompress: {
        forceRequestEncoding: 'gzip'
      }
    }
  }, (req, reply) => {
    // ...
  })

requestEncodings

By default, fastify-compress accepts all encodings specified at the beginning of §Usage - Decompress request payloads. You can change that by passing an array of compression tokens to the requestEncodings option:

fastify.register(
  require('fastify-compress'),
  // Only support gzip
  { requestEncodings: ['gzip'] }
)

forceRequestEncoding

By default, fastify-compress chooses the decompressing algorithm by looking at the content-encoding header, if present.

You can force one algorithm and ignore the header at all by providing the forceRequestEncoding option.

Note that if the request payload is not compressed, fastify-compress will try to decompress, resulting in an error.

onUnsupportedRequestEncoding

When the request payload encoding is not supported, you can customize the response error by setting the onUnsupportedEncoding(request, encoding) option to be a function that returns an error.

fastify.register(
  require('fastify-compress'),
  {
     onUnsupportedRequestEncoding: (request, encoding) => {
      return {
        statusCode: 415,
        code: 'UNSUPPORTED',
        error: 'Unsupported Media Type',
        message: 'We do not support the ' + encoding + ' encoding.'
      }
    }
  }
)

onInvalidRequestPayload

When the request payload cannot be decompressed using the detected algorithm, you can customize the response error setting the onInvalidRequestPayload(request, encoding) option to be a function that returns an error.

fastify.register(
  require('fastify-compress'),
  {
    onInvalidRequestPayload: (request, encoding, error) => {
      return {
        statusCode: 400,
        code: 'BAD_REQUEST',
        error: 'Bad Request',
        message: 'This is not a valid ' + encoding + ' encoded payload: ' + error.message
      }
    }
  }
)

Note

Please note that in large-scale scenarios, you should use a proxy like Nginx to handle response compression.

Acknowledgements

Past sponsors:

License

Licensed under MIT.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].