Getting Started with Compression in Node.js


While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

Compression in Node.js and Express decreases the downloadable amount of data that’s served to users. Through the use of this compression, we can improve the performance of our Node.js applications as our payload size is reduced drastically.

There are two methods of compression. One is calling it directly in your Node.js app using the compression middleware, and the other is to use it at a reverse proxy level through software like NGINX.

How To Set Up Compression

To start using compression in your Node.js application, you can use the compression middleware in the main file of your Node.js app. This will enable GZIP, which supports different compression schemes. This will make your JSON response and other static file responses smaller.

First, you’ll need to install the npm package for compression:

$ npm i compression --save

Then you can use the module in your application after you initialize your server, like with Express.js:

const compression = require('compression');
const express = require('express');

const app = express();

// compress all responses

app.get('/', (req, res) => {
  const animal = 'alligator';
  // Send a text/html file back with the word 'alligator' repeated 1000 times

// ...

In the example above, we call a GET operation that will send back a text/html file with the word alligator printed 1000 times. Without compression, the response would come back with a size of around 9kb.

If you turn on compression, the response is sent with a header that states Content-Encoding: gzip, and instead is only 342B.

Options For Compression

In addition to the default setting, you can customize your compression to fit your use case. There are several different properties that you can use in the options object. To get a full list of properties that you can choose, check out the compression documentation.

To add the options for your compression, your code will look a little something like this:

const shouldCompress = (req, res) => {
  if (req.headers['x-no-compression']) {
    // don't compress responses if this request header is present
    return false;

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

  // filter decides if the response should be compressed or not, 
  // based on the `shouldCompress` function above
  filter: shouldCompress,
  // threshold is the byte threshold for the response body size
  // before compression is considered, the default is 1kb
  threshold: 0

And there you have it! Make sure you use compression for your Node.js app to keep your payload sizes small and snappy!

Creative Commons License