Learn How To Compress Your Responses With Express and Node.js

by | Aug 8, 2020 | 0 comments

const express = require('express');
const port = process.env.PORT || 3000;

// Init express
const app = express();

// Server routes
app.get('/compress', (req, res) => {
  res.send('Hello World!');
});

// Start server
app.listen(port, () => {
  console.log(`Listening on port: ${port}`);
});
npm install compression
const compression = require('compression')
...
...
// Init express
const app = express();

app.use(compression())
...
...

To control the compression level we need the pass a number between 0 – 9 to the level property.

0 – no compression at all.

9  – the best compression available.

The higher the level of compression you use the more time it will take to compress your response.

We can set the default compression by not passing any parameters to the level property or by passing the value -1, this value will currently equal the value of 6 and it means it is the best compromise between compression and speed.

Example of setting a compression level:

app.use(compression({ level: 9 }))
const shouldCompress = (req, res) => {
  if (req.headers['x-no-compression']) {
    // don't compress responses with this request header
    return false;
  }

  // fallback to standard filter function
  return compression.filter(req, res);
};

// Usage:
app.use(compression({ filter: shouldCompress }))
// npm install node-fetch...
const fetch = require('node-fetch');

fetch('http://localhost:3000/compress', {
  method: 'GET',
  headers: {
    'x-no-compression': 'Any true value',
  },
}).catch((e) => console.log(e));
app.get('/compress', (req, res) => {
  // I've shortend the actual text size
  const text = `Lorem Ipsum is simply dummy text of the ...`;
  res.send(text.repeat(10));
});
before-gzip-compression
after-gzip-compression

While I have not looked up the implementation of the gzip algorithm, the most basic compression algorithms usually finds repeating patterns in a given text and replaces them with a representing value instead, by doing so you can compress the text with values that later decompresses to the pattern found.

I hope you enjoyed this article and that it brought you VALUE.

Documentation about the compression plugin:
http://expressjs.com/en/resources/middleware/compression.html

IF YOU GOT ANY VALUE SHARE 😄