Product
Introducing License Enforcement in Socket
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
compression
Advanced tools
The compression npm package is a middleware for Node.js that enables response compression, typically used with Express.js. It can compress response bodies for requests that traverse through the middleware, thus reducing the size of the response sent to clients and improving web application performance.
Compress response bodies
This code demonstrates how to use the compression middleware in an Express.js application to compress response bodies for all routes.
const express = require('express');
const compression = require('compression');
const app = express();
// Use compression middleware
app.use(compression());
// Example route
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000);
Filter requests to compress
This code shows how to use a custom filter function to decide whether to compress responses based on the request headers.
const express = require('express');
const compression = require('compression');
const app = express();
// Compression options with filter
const shouldCompress = (req, res) => {
if (req.headers['x-no-compression']) {
// Don't compress responses if this request header is present
return false;
}
// Fallback to the standard compression filter function
return compression.filter(req, res);
};
app.use(compression({ filter: shouldCompress }));
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000);
shrink-ray-current is an npm package that offers response compression using Brotli and Zopfli, which can provide better compression ratios than the default zlib library used by compression. It is a modern alternative to compression with additional features like cache-friendly ETag support and streaming compression.
koa-compress is a compression middleware for Koa, another popular Node.js web framework. It provides similar functionality to compression but is designed specifically for the Koa ecosystem. It supports various compression algorithms like gzip, deflate, and brotli.
fastify-compress is a plugin for the Fastify web framework that provides response compression capabilities. It supports 'gzip', 'deflate', and 'brotli' encoding methods and allows for custom compression options. It is similar to compression but tailored for use with Fastify.
Node.js compression middleware.
$ npm install compression
var compression = require('compression')
Returns the compression middleware using the given options
.
app.use(compression({
threshold: 512
}))
compression()
accepts these properties in the options object. In addition to
those listed below, zlib options may be
passed in to the options object.
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.
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".
-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
7
8
9
Best compression (also zlib.Z_BEST_COMPRESSION
).Note in the list above, zlib
is from zlib = require('zlib')
.
The byte threshold for the response body size before compression is considered
for the response, defaults to 1kb
. This is a number of bytes, any string
accepted by the bytes module, or false
.
The default filter
function. This is used to construct a custom filter
function that is an extension of the default function.
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.
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 requests
app.use(compression())
// add all routes
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)
})
})
FAQs
Node.js compression middleware
The npm package compression receives a total of 11,335,327 weekly downloads. As such, compression popularity was classified as popular.
We found that compression demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
Product
We're launching a new set of license analysis and compliance features for analyzing, managing, and complying with licenses across a range of supported languages and ecosystems.
Product
We're excited to introduce Socket Optimize, a powerful CLI command to secure open source dependencies with tested, optimized package overrides.