Skip to content

Express js optimize performance with GZIP Compression

Last updated on November 21, 2022

You can improve speed and save bandwidth by using GZIP compression in your express js application. GZIP actually decreases the downloadable amount of data for the user’s request.

Without GZIP compression, when you request a file like http://example.com/about.html, your browser talks to a web server and returns plain HTML without compression, if you enable GZIP compression the server will return a compressed version of data. Then the browser could download the zipped file, extract it, and then show it to the user. The amount of data that you download for the zipped version is lesser the plan version, which means you are saving bandwidth and download time, less user waiting time means faster page loading.

Express js optimize performance with GZIP Compression

Express Js – GZIP compression

You can use the compression middleware to enable GZIP which will support deflate,gzip compression schemes. This middleware will compact the JSON response and the entire static files response. First, let’s install it

npm install compression --save

After installing it, it will be necessary to include its middleware in the server.js or in our middleware list.

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

let oneYear = 1 * 365 * 24 * 60 * 60 * 1000;

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

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

app.get('/',function(req,res){
    res.send('hello world');
});

app.listen(8080,function(){
    console.log('project started');
});

you can start the server by running

npm server.js

Now head over to http://localhost:8080, you can see that the page was served gzipped via the Content-Encoding: gzip header. You can verify the static assets cache by observing the following, for the first time page should have 200 response, for page refresh (ctrl + R) it should have a 304 response code, for doing the hard refresh (ctrl + shift + R) it should show 200 response.

0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments