Koa.js – Compression

  • Post author:
  • Post category:Koa.js
  • Post comments:0 Comments

Compression is a simple, effective way to save bandwidth and speed up your site. It is only compatible with modern browsers and should be used with caution if your users use legacy browsers as well.

When sending responses from the server, if compression is used, it can greatly improve the load time. We’ll be using a middleware called koa-compress to take care of the compression of files as well as setting appropriate headers.

Go ahead and install the middleware using −

$ npm install --save koa-compress

Now in your app.js file, add the following code −

var koa = require('koa');
var router = require('koa-router');
var app = koa();

var Pug = require('koa-pug');
var pug = new Pug({
   viewPath: './views',
   basedir: './views',
   app: app //Equivalent to app.use(pug)
});

app.use(compress({
   filter: function (content_type) {
      return /text/i.test(content_type)
   },
   threshold: 2048,
   flush: require('zlib').Z_SYNC_FLUSH
}));

var _ = router(); //Instantiate the router

_.get('/', getRoot);

function *getRoot(next){
   this.render('index');
}

app.use(_.routes()); //Use the routes defined using the router
app.listen(3000);

This puts our compression middleware in place. The filter option is a function that checks the response content type to decide whether to compress. The threshold option is the minimum response size in bytes to compress. This ensures we don’t compress every little response.

Following is a response without compression.

Compression

Following is the similar response with compression.

Compression

If you look at the size tab at the bottom, you can very well see the difference between the two. There is more than 150% improvement, when we compress the files.

Next Topic:-Click Here

Leave a Reply