compression

repository·master·Indexed 25 days ago

https://github.com/expressjs/compression

Node.js compression middleware (v1.8.1) that reduces response body sizes using gzip, deflate, and Brotli codings. It can be used with Express via app.use(compression()) or with standard Node.js HTTP servers. The middleware supports configurable thresholds, custom filters, and provides a res.flush() method for streaming data like Server-Sent Events (SSE). It respects the Cache-Control no-transform directive and only compresses content deemed compressible.

Tokens
1.9K
Snippets
5
Records
11
Agent score
34%

What's inside compression

  1. Use compression with a Node.js HTTP server

    master

    For a standard Node.js HTTP server, wrap your request handler with the compression middleware. Note that when using it manually, you should pass an options object (e.g., { threshold: 0 }) to initialize it.

    var compression = require('compression')({ threshold: 0 })
    var http = require('http')
    
    function createServer (fn) {
      return http.createServer(function (req, res) {
        compression(req, res, function (err) {
          if (err) {
            res.statusCode = err.status || 500
            res.end(err.message)
            return
          }
    
          fn(req, res)
        })
      })
    }
    
    var server = createServer(function (req, res) {
      res.setHeader('Content-Type', 'text/plain')
      res.end('hello world!')
    })
    
    server.listen(3000, () => {
      console.log('> Listening at http://localhost:3000')
    })
  2. Use compression with Server-Sent Events (SSE)

    master

    Because compression buffers output to achieve better ratios, it can delay data in streams like Server-Sent Events. To ensure data reaches the client in a timely manner, call res.flush() after writing data chunks.

    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)
      })
    })
  3. Use compression middleware with Express

    master

    To compress all responses in an Express application, use app.use(compression()). You can place this middleware as high as needed in your middleware stack.

    var compression = require('compression')
    var express = require('express')
    
    var app = express()
    
    // compress all responses
    app.use(compression())
    
    // add all routes
  4. Flush partially-compressed responses with res.flush()

    master
    The compression module adds a res.flush() method to the response object. This allows you to force the partially-compressed response buffer to be sent to the client immediately. This is particularly useful for streaming data like Server-Sent Events (SSE).
  5. Configure compression options

    master

    The compression([options]) function returns middleware that attempts to compress response bodies based on the provided configuration.

    Supported Codings:

    • deflate
    • gzip
    • br (Brotli) — Note: Brotli requires Node.js v11.7.0+ or v10.16.0+.

    Important Behavior: The middleware will never compress responses that include a Cache-Control header with the no-transform directive.

  6. Customize the compression filter

    master

    You can provide a custom filter function in the options to control which responses are compressed. You can extend the default filter using compression.filter(req, res) to maintain standard behavior for compressible content types while adding custom logic.

    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)
    }
  7. Configure compression options

    master

    You can pass an options object to compression() to customize its behavior:

    • filter: A function used to determine if a response should be compressed. Defaults to shouldCompress (checks if Content-Type is compressible).
    • threshold: A value (can be a string like '1kb' or a number in bytes) representing the minimum response size required for compression to occur. Defaults to 1024 bytes.
    • enforceEncoding: The encoding to use if the request has no Accept-Encoding header. Defaults to 'identity'.
    • brotli: An object containing options for Brotli compression. If provided, these options are passed to zlib.createBrotliCompress. Note that the default BROTLI_PARAM_QUALITY is set to 4 if not specified.
  8. Reference: compression() options

    master

    The following options can be passed to compression() to configure the middleware behavior. Many options correspond to zlib settings.

    OptionTypeDefaultDescription
    chunkSizeNumber16384Size of the chunks used for compression.
    filterFunction(default)A function filter(req, res) that returns true to compress or false to skip. The default uses the compressible module on res.getHeader('Content-Type').
    levelNumber-1zlib compression level (0-9). -1 is default.
    memLevelNumber8Memory allocated for internal compression state (1-9).
    brotliObjectundefinedConfiguration options for Brotli compression.
    strategyNumberzlib.constants.Z_DEFAULT_STRATEGYTuning for the compression algorithm (e.g., Z_FILTERED, Z_HUFFMAN_ONLY).
    thresholdNumber or String1kbByte threshold before compression is applied. Accepts strings via bytes module (e.g., '1kb').
    windowBitsNumber15zlib window bits.
    enforceEncodingString'identity'Default encoding to use if client doesn't specify one in Accept-Encoding.
  9. Use the compression middleware

    master

    The compression function returns a middleware function for Express/Node.js that automatically compresses response bodies using gzip, deflate, or br (Brotli) based on the request's Accept-Encoding header. It respects the Content-Type of the response and only compresses content that is deemed compressible.

    By default, it only compresses responses larger than 1024 bytes.

  10. Use res.flush() to flush compression stream

    master
    The compression middleware adds a flush method to the res (response) object. Calling res.flush() will flush the compression stream, allowing you to send data to the client immediately even if the compression buffer is not yet full. This is useful for streaming responses or real-time data.