Thursday, March 2, 2017

Koa.js - Caching

Caching is the term for storing reusable responses in order to make subsequent requests faster. Every browser ships with an implementation of an 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.

Here are some benefits of including caching in your webapps:
  • 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
Now 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 client side. The cache-control header is set according to options we provide while initializing the cache object. We have set the expiration time of this cached response to 1 year. Below are the comparision of requests we have sent before and after the file was cached.
Before this file was cached, the returned status code was 200, ie, OK. The response headers had multiple information regarding the content to be cached and had also given us an ETag for the content.
The next time the request was sent, it was sent along with the etag. 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.
NOTE: For invalidating any cached file, you just need to change its file name and update the reference to it. This will ensure that you have a new file to send to the client and client cant load it back from the cache.

No comments:

Post a Comment