Node.js compression middleware.
The following compression codings are supported:
- deflate
- gzip
- br (brotli)
This is a Node.js module available through the
npm registry. Installation is done using the
npm install command:
$ npm install compressionvar compression = require('compression')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.
compression() accepts these properties in the options object.
Type: Object
Handles the configurations for each encoding. Setting options.encodings[encoding] = false will disable that encoding.
Example:
const compression = require('compression')
const express = require('express')
const app = express()
app.use(
compression({
encodings: {
br: {
params: {
[zlib.constants.BROTLI_PARAM_QUALITY]: 6
}
},
gzip: {
level: zlib.constants.Z_BEST_SPEED
},
deflate: false // Disable Deflate compression
}
})
)br(Brotli):
This specifies the options for configuring Brotli. See Node.js documentation for a complete list of available options.
- gzip:
This specifies the options for configuring gzip. See Node.js documentation for a complete list of available options.
- deflate:
This specifies the options for configuring deflate. See Node.js documentation for a complete list of available options.
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.
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.
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.
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)
}This module adds a res.flush() method to force the partially-compressed
response to be flushed to the client. This function accepts a callback which gets
invoked when the response has been flushed to the client
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 routesvar 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')
})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)
})
})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.