compression vs koa-compress vs express-static-gzip
Node.js Middleware for Compression Comparison
1 Year
compressionkoa-compressexpress-static-gzipSimilar Packages:
What's Node.js Middleware for Compression?

These npm packages are designed to optimize the performance of web applications by compressing HTTP responses, thereby reducing the amount of data sent over the network. This is particularly important for improving load times and enhancing the overall user experience, especially for applications serving large assets or data-heavy responses. Each package has its unique features and use cases, catering to different frameworks and requirements in Node.js applications.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
compression20,789,8892,78527.5 kB2422 days agoMIT
koa-compress375,51744012.6 kB72 years agoMIT
express-static-gzip115,79314824.4 kB34 months agoMIT
Feature Comparison: compression vs koa-compress vs express-static-gzip

Framework Compatibility

  • compression:

    Designed specifically for Express.js, 'compression' integrates easily into existing Express applications, allowing for quick setup and configuration.

  • koa-compress:

    Tailored for Koa.js, 'koa-compress' leverages Koa's middleware architecture, allowing for effective compression in Koa applications, particularly those using async functions.

  • express-static-gzip:

    Built for Express.js as well, 'express-static-gzip' combines static file serving with compression, making it ideal for serving static assets efficiently within Express applications.

Compression Strategy

  • compression:

    Utilizes Gzip compression by default, providing an easy way to reduce the size of HTTP responses. It can be configured to set thresholds for compression, ensuring that only larger responses are compressed to save CPU resources.

  • koa-compress:

    Supports Gzip and Brotli compression, offering flexibility in compression strategies. This allows developers to choose the most efficient method for their specific use case.

  • express-static-gzip:

    Automatically serves pre-compressed Gzip files if they exist, falling back to uncompressed files if not. This strategy can significantly speed up response times for static assets, as it minimizes processing overhead.

Performance Impact

  • compression:

    By compressing responses, 'compression' can significantly reduce the amount of data transferred over the network, leading to faster load times and improved performance, especially for large payloads.

  • koa-compress:

    Optimizes response sizes in Koa applications, ensuring that bandwidth is used efficiently and improving the overall speed of data delivery to clients.

  • express-static-gzip:

    This package enhances performance by serving pre-compressed files, which can drastically reduce response times for static assets, making it particularly effective for high-traffic applications.

Configuration Options

  • compression:

    Offers various configuration options, such as setting minimum response sizes for compression and customizing the compression level, allowing developers to fine-tune performance based on their application's needs.

  • koa-compress:

    Allows configuration of compression thresholds and methods, enabling developers to optimize performance based on the specific requirements of their Koa applications.

  • express-static-gzip:

    Provides options for cache control and setting up custom routes for static files, giving developers control over how static assets are served and cached.

Ease of Use

  • compression:

    Very easy to implement with just a few lines of code in an Express application, making it accessible for developers of all skill levels.

  • koa-compress:

    Integrates seamlessly with Koa's middleware system, providing a straightforward implementation for compressing responses in Koa applications.

  • express-static-gzip:

    Combines static file serving and compression in one package, simplifying the process of serving compressed static assets without additional middleware.

How to Choose: compression vs koa-compress vs express-static-gzip
  • compression:

    Choose 'compression' if you are using Express.js and need a straightforward middleware solution for Gzip compression. It is simple to implement and works well with various types of responses, making it a versatile choice for general use cases.

  • koa-compress:

    Select 'koa-compress' if you are working with Koa.js and need a middleware that efficiently compresses responses. This package is tailored for Koa's async/await syntax, providing a seamless integration for modern JavaScript applications.

  • express-static-gzip:

    Opt for 'express-static-gzip' if you want to serve static files with built-in Gzip compression support. This package is ideal for applications that serve a lot of static assets, as it combines static file serving and compression in one middleware, improving performance without additional configuration.

README for compression

compression

NPM Version NPM Downloads Build Status OpenSSF Scorecard Badge Funding

Node.js compression middleware.

The following compression codings are supported:

  • deflate
  • gzip
  • br (brotli)

Note Brotli is supported only since Node.js versions v11.7.0 and v10.16.0.

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 or brotli options.

chunkSize

Type: Number
Default: zlib.constants.Z_DEFAULT_CHUNK, or 16384.

See Node.js documentation regarding the usage.

filter

Type: Function

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

Type: Number
Default: zlib.constants.Z_DEFAULT_COMPRESSION, or -1

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.constants.Z_DEFAULT_COMPRESSION).
  • 0 No compression (also zlib.constants.Z_NO_COMPRESSION).
  • 1 Fastest compression (also zlib.constants.Z_BEST_SPEED).
  • 2
  • 3
  • 4
  • 5
  • 6 (currently what zlib.constants.Z_DEFAULT_COMPRESSION points to).
  • 7
  • 8
  • 9 Best compression (also zlib.constants.Z_BEST_COMPRESSION).

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

memLevel

Type: Number
Default: zlib.constants.Z_DEFAULT_MEMLEVEL, or 8

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).

See Node.js documentation regarding the usage.

brotli

Type: Object

This specifies the options for configuring Brotli. See Node.js documentation for a complete list of available options.

strategy

Type: Number
Default: zlib.constants.Z_DEFAULT_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.constants.Z_DEFAULT_STRATEGY Use for normal data.
  • zlib.constants.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.constants.Z_DEFAULT_STRATEGY and zlib.constants.Z_HUFFMAN_ONLY.
  • zlib.constants.Z_FIXED Use to prevent the use of dynamic Huffman codes, allowing for a simpler decoder for special applications.
  • zlib.constants.Z_HUFFMAN_ONLY Use to force Huffman encoding only (no string match).
  • zlib.constants.Z_RLE Use to limit match distances to one (run-length encoding). This is designed to be almost as fast as zlib.constants.Z_HUFFMAN_ONLY, but give better compression for PNG image data.

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

threshold

Type: Number or String
Default: 1kb

The byte threshold for the response body size before compression is considered for the response. 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

Type: Number
Default: zlib.constants.Z_DEFAULT_WINDOWBITS, or 15

See Node.js documentation regarding the usage.

enforceEncoding

Type: String
Default: identity

This is the default encoding to use when the client does not specify an encoding in the request's Accept-Encoding header.

.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

When using this module with express, 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

Node.js HTTP server

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')
})

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)
  })
})

Contributing

The Express.js project welcomes all constructive contributions. Contributions take many forms, from code for bug fixes and enhancements, to additions and fixes to documentation, additional tests, triaging incoming pull requests and issues, and more!

See the Contributing Guide for more technical details on contributing.

License

MIT