Koa.js - Caching


Advertisements

Caching is the term for storing reusable responses in order to make subsequent requests faster. Every browser ships with an implementation of a HTTP cache. All we have to do is ensure that each server response provides correct HTTP header directives to instruct the browser on when and for how long the response can be cached by the browser.

Following are some benefits of including caching in your web apps −

  • Your network costs decrease. If your content is cached, you'll need to send less of it for every subsequent request.

  • Speed and performance of your website increases.

  • Your content can be made available even if your client is offline.

We'll be using the koa-static-cache middleware to implement caching in our app. Install these middleware using −

$ npm install --save koa-static-cache

Go to your app.js file and add the following code to it.

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

var path = require('path');
var staticCache = require('koa-static-cache');

app.use(staticCache(path.join(__dirname, 'public'), {
   maxAge: 365 * 24 * 60 * 60  //Add these files to caches for a year
}))

app.listen(3000);

The koa-static-cache middleware is used to cache server responses on the client side. The cache-control header is set according to the options we provide while initializing the cache object. We have set the expiration time of this cached response to 1 year. Following are the comparisons of request we have sent before and after the file was cached.

Before this file was cached, the returned status code was 200, which is OK. The response headers had multiple information regarding the content to be cached and had also given an ETag for the content.

Before Cache

The next time the request was sent, it was sent along with the ETtag. Since our content hadn't changed on the server, its corresponding ETag also remained the same and the client was told that the copy it has locally is up-to-date with what the server would provide and should use the local one instead of requesting again.

After Cache

Note − For invalidating any cached file, you just need to change its file name and update its reference. This will ensure that you have a new file to send to the client and the client can’t load it back from the cache.

Advertisements