ScanSkill
Sign up for daily dose of tech articles at your inbox.
Loading

How To Compress API In Express

How To Compress API In Express
How To Compress API In Express

Let’s learn how to compress API in Express. We are going to achieve this by compressing the response sent by the server to the client.

Introduction

Compression of APIs is common practice in the backend, in the production environment. It reduces the size of content sent by the server back to the client. It makes two important things possible to be achieved those are: faster response time and improved performance in general. In the production environment, we compress, most of the responses that are sent back to the client.

Compressing responses in REST APIs makes it so that the load that the network is reduced, and the load is handled at the expense of the CPU. Compressing anything depends on the CPU, which is generally more abundant in the server environment than high network resources. So in many cases using compression in the backend for responses sent back to the client by the server becomes feasible.

Two popular algorithms are used to achieve this, which include GZip and Deflate because most modern browsers recognize these algorithms. So, we have looked into the reason, and why compression is done, let’s look at how to compress API in Express.

Prerequisites

Compress API In Express

Firstly before getting straight into compression, let’s get started by initializing a node project, creating an index.js file which will be the starting point for the application, and installing express.

## Initializing a node project
$ npm init -y

## creating index.js, start point for our application
$ touch index.js

## Installing the express package
$ npm install express
Starting file for the node application
Starting file for the node application

For achieving compression in Express, we need to add an external node module called compression. This Module is available in npm, so to install the package:

$ npm install compression
Installing the compression module
Installing the compression module

Let’s start by creating an API endpoint, through which we will test the use of compression.

index.js

Let’s first create, the application without compression.

// index.js

const app = require("express")();

app.get("/", (req, res) => {
  const payload = "hello".repeat(500000);
  res.send(payload);
});

app.listen(3000, console.log("Server started on PORT -> 3000"));

The repeat() method repeats the string "hello" for 500000 times as it’s given in the payload.

Response without using compression
Response without using compression

The response time is 148 ms, and the payload size is 2.5 MB. Now, that we have checked the response let’s integrate the compression module. First, let’s check out the default configuration.

const app = require("express")();
const compression = require("compression");

app.use(compression());

app.get("/", (req, res) => {
  const payload = "hello".repeat(500000);
  res.send(payload);
});

app.listen(3000, console.log("Server started on PORT -> 3000"));

Let’s check this at the default configuration provided by the compression module. The compression module when initialized provides us with a middleware that in the above case when used with app.use(), compresses all the responses that go out of the server.

Compress API In Express
Response when using the compression module

The response time is 73 ms, and the payload size is 4.0 KB. So we can see the file size is smaller than previously. While using the compression module.

Area Of StudyWithout CompressionWith Compression
Time148 ms73 ms
size2.5 MB4.0 kB
Table of comparison between using compression and not using it

By looking into the table above we can see a huge percentile difference between the time and size of the payload without and with using compression. So we can see the difference.

The compression middleware provides additional options, let’s look at those options.

Compression Options

Using different options provided by the compression middleware, you can compress your responses to better fit your needs. Let’s look at the options provided by the compression middleware to compress API in Express.

filter

It provides the information to the compression middleware if the response should be compressed or not.

const compressionFilter = (req, res) => {
  if(req.headers['x-no-compression']) {
    return false;
  }
  return true;
}

app.use(compression({
  filter: compressionFilter,
}));

In the above code, the function compressionFilter checks if in header sent by the client has the x-no-compression or not if it has then it returns false telling the compression middleware to not compress the response. Else it compresses the returned response.

threshold

It provides the bytes before the compression is done. By default, it is 1 kB.

app.use(compression({
  threshold: 24
}));

In the above code, the threshold option provided takes in a parameter that is in bytes. The 24 in the code, it uses compression only after the response payload which is sent back as the response exceeds 24 kB in size.

Conclusion

So, in this article, we learned about how to compress API in Express. We saw the practical use of the compression middleware provided by the compression package, implemented it, and also saw the results on time and the size of the response sent to the client. The compression reduced the load on the network. To reduce the load on the server by continuous API trigger by the same client look into this article about rate limiting.

Sign up for daily dose of tech articles at your inbox.
Loading