Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

compression

expressjs61.9mMIT1.7.5TypeScript support: definitely-typed

Node.js compression middleware

readme

compression

NPM Version NPM Downloads Build Status Test Coverage

Node.js compression middleware.

The following compression codings are supported:

  • deflate
  • gzip

Install

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

$ npm install compression

API

var compression = require('compression')

compression([options])

Returns the compression middleware using the given options. The middleware will attempt to compress response bodies for all requests that traverse through the middleware, based on the given options.

This middleware will never compress responses that include a Cache-Control header with the no-transform directive, as compressing will transform the body.

Options

compression() accepts these properties in the options object. In addition to those listed below, zlib options may be passed in to the options object.

chunkSize

The default value is zlib.Z_DEFAULT_CHUNK, or 16384.

See Node.js documentation regarding the usage.

filter

A function to decide if the response should be considered for compression. This function is called as filter(req, res) and is expected to return true to consider the response for compression, or false to not compress the response.

The default filter function uses the compressible module to determine if res.getHeader('Content-Type') is compressible.

level

The level of zlib compression to apply to responses. A higher level will result in better compression, but will take longer to complete. A lower level will result in less compression, but will be much faster.

This is an integer in the range of 0 (no compression) to 9 (maximum compression). The special value -1 can be used to mean the "default compression level", which is a default compromise between speed and compression (currently equivalent to level 6).

  • -1 Default compression level (also zlib.Z_DEFAULT_COMPRESSION).
  • 0 No compression (also zlib.Z_NO_COMPRESSION).
  • 1 Fastest compression (also zlib.Z_BEST_SPEED).
  • 2
  • 3
  • 4
  • 5
  • 6 (currently what zlib.Z_DEFAULT_COMPRESSION points to).
  • 7
  • 8
  • 9 Best compression (also zlib.Z_BEST_COMPRESSION).

The default value is zlib.Z_DEFAULT_COMPRESSION, or -1.

Note in the list above, zlib is from zlib = require('zlib').

memLevel

This specifies how much memory should be allocated for the internal compression state and is an integer in the range of 1 (minimum level) and 9 (maximum level).

The default value is zlib.Z_DEFAULT_MEMLEVEL, or 8.

See Node.js documentation regarding the usage.

strategy

This is used to tune the compression algorithm. This value only affects the compression ratio, not the correctness of the compressed output, even if it is not set appropriately.

  • zlib.Z_DEFAULT_STRATEGY Use for normal data.
  • zlib.Z_FILTERED Use for data produced by a filter (or predictor). Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. The effect is to force more Huffman coding and less string matching; it is somewhat intermediate between zlib.Z_DEFAULT_STRATEGY and zlib.Z_HUFFMAN_ONLY.
  • zlib.Z_FIXED Use to prevent the use of dynamic Huffman codes, allowing for a simpler decoder for special applications.
  • zlib.Z_HUFFMAN_ONLY Use to force Huffman encoding only (no string match).
  • zlib.Z_RLE Use to limit match distances to one (run-length encoding). This is designed to be almost as fast as zlib.Z_HUFFMAN_ONLY, but give better compression for PNG image data.

Note in the list above, zlib is from zlib = require('zlib').

threshold

The byte threshold for the response body size before compression is considered for the response, defaults to 1kb. This is a number of bytes or any string accepted by the bytes module.

Note this is only an advisory setting; if the response size cannot be determined at the time the response headers are written, then it is assumed the response is over the threshold. To guarantee the response size can be determined, be sure set a Content-Length response header.

windowBits

The default value is zlib.Z_DEFAULT_WINDOWBITS, or 15.

See Node.js documentation regarding the usage.

.filter

The default filter function. This is used to construct a custom filter function that is an extension of the default function.

var compression = require('compression')
var express = require('express')

var app = express()
app.use(compression({ filter: shouldCompress }))

function shouldCompress (req, res) {
  if (req.headers['x-no-compression']) {
    // don't compress responses with this request header
    return false
  }

  // fallback to standard filter function
  return compression.filter(req, res)
}

res.flush

This module adds a res.flush() method to force the partially-compressed response to be flushed to the client.

Examples

express/connect

When using this module with express or connect, simply app.use the module as high as you like. Requests that pass through the middleware will be compressed.

var compression = require('compression')
var express = require('express')

var app = express()

// compress all responses
app.use(compression())

// add all routes

Server-Sent Events

Because of the nature of compression this module does not work out of the box with server-sent events. To compress content, a window of the output needs to be buffered up in order to get good compression. Typically when using server-sent events, there are certain block of data that need to reach the client.

You can achieve this by calling res.flush() when you need the data written to actually make it to the client.

var compression = require('compression')
var express = require('express')

var app = express()

// compress responses
app.use(compression())

// server-sent event stream
app.get('/events', function (req, res) {
  res.setHeader('Content-Type', 'text/event-stream')
  res.setHeader('Cache-Control', 'no-cache')

  // send a ping approx every 2 seconds
  var timer = setInterval(function () {
    res.write('data: ping\n\n')

    // !!! this is the important part
    res.flush()
  }, 2000)

  res.on('close', function () {
    clearInterval(timer)
  })
})

License

MIT

changelog

1.7.5 / 2024-10-31

  • deps: Replace accepts with negotiator@~0.6.4
    • Add preference option
  • deps: bytes@3.1.2
    • Add petabyte (pb) support
    • Fix "thousandsSeparator" incorrecting formatting fractional part
    • Fix return value for un-parsable strings
  • deps: compressible@~2.0.18
    • Mark font/ttf as compressible
    • Remove compressible from multipart/mixed
    • deps: mime-db@'>= 1.43.0 < 2'
  • deps: safe-buffer@5.2.1

1.7.4 / 2019-03-18

  • deps: compressible@~2.0.16
    • Mark text/less as compressible
    • deps: mime-db@'>= 1.38.0 < 2'
  • deps: on-headers@~1.0.2
    • Fix res.writeHead patch missing return value
  • perf: prevent unnecessary buffer copy

1.7.3 / 2018-07-15

  • deps: accepts@~1.3.5
    • deps: mime-types@~2.1.18
  • deps: compressible@~2.0.14
    • Mark all XML-derived types as compressible
    • deps: mime-db@'>= 1.34.0 < 2'
  • deps: safe-buffer@5.1.2

1.7.2 / 2018-02-18

  • deps: compressible@~2.0.13
    • deps: mime-db@'>= 1.33.0 < 2'

1.7.1 / 2017-09-26

  • deps: accepts@~1.3.4
    • deps: mime-types@~2.1.16
  • deps: bytes@3.0.0
  • deps: compressible@~2.0.11
    • deps: mime-db@'>= 1.29.0 < 2'
  • deps: debug@2.6.9
  • deps: vary@~1.1.2
    • perf: improve header token parsing speed

1.7.0 / 2017-07-10

  • Use safe-buffer for improved Buffer API
  • deps: bytes@2.5.0
  • deps: compressible@~2.0.10
    • Fix regex fallback to not override compressible: false in db
    • deps: mime-db@'>= 1.27.0 < 2'
  • deps: debug@2.6.8
    • Allow colors in workers
    • Deprecated DEBUG_FD environment variable set to 3 or higher
    • Fix error when running under React Native
    • Fix DEBUG_MAX_ARRAY_LENGTH
    • Use same color for same namespace
    • deps: ms@2.0.0
  • deps: vary@~1.1.1
    • perf: hoist regular expression

1.6.2 / 2016-05-12

  • deps: accepts@~1.3.3
  • deps: bytes@2.3.0
    • Drop partial bytes on all parsed units
    • Fix parsing byte string that looks like hex
    • perf: hoist regular expressions
  • deps: compressible@~2.0.8
    • deps: mime-db@'>= 1.23.0 < 2'

1.6.1 / 2016-01-19

  • deps: bytes@2.2.0
  • deps: compressible@~2.0.7
    • deps: mime-db@'>= 1.21.0 < 2'
  • deps: accepts@~1.3.1
    • deps: mime-types@~2.1.9

1.6.0 / 2015-09-29

  • Skip compression when response has Cache-Control: no-transform
  • deps: accepts@~1.3.0
  • deps: compressible@~2.0.6
    • deps: mime-db@'>= 1.19.0 < 2'
  • deps: on-headers@~1.0.1
    • perf: enable strict mode
  • deps: vary@~1.1.0
    • Only accept valid field names in the field argument

1.5.2 / 2015-07-30

  • deps: accepts@~1.2.12
    • deps: mime-types@~2.1.4
  • deps: compressible@~2.0.5
    • deps: mime-db@'>= 1.16.0 < 2'
  • deps: vary@~1.0.1
    • Fix setting empty header from empty field
    • perf: enable strict mode
    • perf: remove argument reassignments

1.5.1 / 2015-07-05

  • deps: accepts@~1.2.10
    • deps: mime-types@~2.1.2
  • deps: compressible@~2.0.4
    • deps: mime-db@'>= 1.14.0 < 2'
    • perf: enable strict mode

1.5.0 / 2015-06-09

  • Fix return value from .end and .write after end
  • Improve detection of zero-length body without Content-Length
  • deps: accepts@~1.2.9
    • deps: mime-types@~2.1.1
    • perf: avoid argument reassignment & argument slice
    • perf: avoid negotiator recursive construction
    • perf: enable strict mode
    • perf: remove unnecessary bitwise operator
  • deps: bytes@2.1.0
    • Slight optimizations
    • Units no longer case sensitive when parsing
  • deps: compressible@~2.0.3
    • Fix regex fallback to work if type exists, but is undefined
    • deps: mime-db@'>= 1.13.0 < 2'
    • perf: hoist regex declaration
    • perf: use regex to extract mime
  • perf: enable strict mode
  • perf: remove flush reassignment
  • perf: simplify threshold detection

1.4.4 / 2015-05-11

1.4.3 / 2015-03-14

  • deps: accepts@~1.2.5
    • deps: mime-types@~2.0.10
  • deps: debug@~2.1.3
    • Fix high intensity foreground color for bold
    • deps: ms@0.7.0

1.4.2 / 2015-03-11

  • Fix error when code calls res.end(str, encoding)
    • Specific to Node.js 0.8
  • deps: debug@~2.1.2

1.4.1 / 2015-02-15

1.4.0 / 2015-02-01

  • Prefer gzip over deflate on the server
    • Not all clients agree on what "deflate" coding means

1.3.1 / 2015-01-31

  • deps: accepts@~1.2.3
    • deps: mime-types@~2.0.8
  • deps: compressible@~2.0.2
    • deps: mime-db@'>= 1.1.2 < 2'

1.3.0 / 2014-12-30

  • Export the default filter function for wrapping
  • deps: accepts@~1.2.2
  • deps: debug@~2.1.1

1.2.2 / 2014-12-10

  • Fix .end to only proxy to .end
    • Fixes an issue with Node.js 0.11.14
  • deps: accepts@~1.1.4
    • deps: mime-types@~2.0.4

1.2.1 / 2014-11-23

  • deps: accepts@~1.1.3
    • deps: mime-types@~2.0.3

1.2.0 / 2014-10-16

  • deps: debug@~2.1.0
    • Implement DEBUG_FD env variable support

1.1.2 / 2014-10-15

  • deps: accepts@~1.1.2

1.1.1 / 2014-10-12

1.1.0 / 2014-09-07

  • deps: accepts@~1.1.0
  • deps: compressible@~2.0.0
  • deps: debug@~2.0.0

1.0.11 / 2014-08-10

  • deps: on-headers@~1.0.0
  • deps: vary@~1.0.0

1.0.10 / 2014-08-05

  • deps: compressible@~1.1.1
    • Fix upper-case Content-Type characters prevent compression

1.0.9 / 2014-07-20

1.0.8 / 2014-06-20

  • deps: accepts@~1.0.5
    • use mime-types

1.0.7 / 2014-06-11

1.0.6 / 2014-06-03

  • fix regression when negotiation fails

1.0.5 / 2014-06-03

  • fix listeners for delayed stream creation
    • fixes regression for certain stream.pipe(res) situations

1.0.4 / 2014-06-03

  • fix adding Vary when value stored as array
  • fix back-pressure behavior
  • fix length check for res.end

1.0.3 / 2014-05-29

  • use accepts for negotiation
  • use on-headers to handle header checking
  • deps: bytes@1.0.0

1.0.2 / 2014-04-29

1.0.1 / 2014-03-08

  • bump negotiator
  • use compressible
  • use .headersSent (drops 0.8 support)
  • handle identity;q=0 case