Compress HTTP Request and Response in Node.js Server

Node.js is taking over the API development zone and knocking every competitor out, but this is not the only place where you can use Node.js server.

Some of the big companies like Uber, Paypal, and Housing are using Node.js as a front-end server. When you deal with front-end and browser, you need to make sure the speed is up to the standard.

The necessary and essential way to make sure speed is optimal is by using compression. In this post, we are going to look at how to compress the request and response of Node.js Server to improve the website speed.

Compression algorithms

There are two types of compression:

  • Lossless
  • Lossy

As the name suggests, we need to focus on compression, which should not lose or corrupt the data. In other words, we need to focus on Lossless compressions.

There are two popular lossless compression algorithms for HTTP:

  • Gzip
  • Deflate

Gzip is also file format and one of the standard ways (RFC 2616) to compress HTTP data.

Compression in Node.js

Let’s write a program to compress HTTP requests and response.

Create a new project.

npm init --y

Install the required dependency.

npm i --S express compression

Here is our app.js.

app.js
var compression = require('compression')
var express = require('express')
var router = express.Router();
var app = express()
 
// compress all requests
app.use(compression())
 
// add all routes
router.get('*',(req,res) => {
    res.write('<h1>Hello World</h1>');
});

app.use('/',router);
app.listen(process.env.PORT || 3000);

Run the program and hit the request from the browser. Every request now would be compressed.

Check out the npm package for more details.

Summary

This is a short tip to compress HTTP request and response. You can also compress images and files using standard algorithms in Node.js. There are plenty of node modules available for such purpose as well.

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 126