DEV Community

Cover image for How To Optimize Performance With GZIP Compression
Pankaj Kumar
Pankaj Kumar

Posted on • Updated on

How To Optimize Performance With GZIP Compression

In this article, I will explain to you one of the very common topics of performance optimization in Node.js express application. While working with any type of application we need to think a lot about performance optimization.

When we come to Node.js express framework specifically, We can improve the performance and save the bandwidth by using GZIP compression. It mainly decreases the downloadable amount of data to serve the user.

When a user makes a request to Node.js server, Normally it does not compress the response anyway.

Let's Get Started

We can use the compression middleware in our main file of Node.js app to enable GZIP which will support compression schemes. This will compact the JSON response and other static files response.

Now install the npm package by typing npm install compression --save over the terminal. After installing it, 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. Have a look below:


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

const app = express()

// compress all responses
app.use(compression())

// add all routes

Enter fullscreen mode Exit fullscreen mode

Understand with an example:


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

let oneDay = 24 * 60 * 60 * 1000;

// compress all responses
app.use(compression());

// Caches the static files for a year.
app.use('/', express.static(__dirname + '/public/', { maxAge: oneDay }));

app.get('/',function(req,res){
res.send('welcome to jsonworld');
});

app.listen(3000,function(){
console.log('app running on port 3000');
});

Enter fullscreen mode Exit fullscreen mode

Conclusion

So in this demo, We learned how to optimize performance with GZIP Compression. Find here other nodejs sample application

That’s all for now. Thank you for reading and I hope this demo will be very helpful to understand how to optimize performance with GZIP Compression.

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.

This article is originally posted over jsonworld

Top comments (0)