Getting Started with Compression in Node.js Apps

569
SHARES
2.6k
VIEWS

Today we will learn how to add compression in node.js applications to significantly improving the website performance by decreasing the size of data that user has to download on every request.

There are basically two methods of compression. One is by using the compression package and calling it directly in your Node.js app, 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 of all, we 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.use(compression());

app.get('/', (req, res) => {
  res.send(animal.repeat(1000));
});

// ...

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

app.use(compression({
  // 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!

Leave a Reply

Your email address will not be published. Required fields are marked *

Trending