Saturday, June 6, 2020

Caching static content in Node.js

Caching Static Content In Node.js

If you feel like the image above is like a poster of horror movie then yes it's true, its because you have to implement caching very carefully. It is very easy to implement at the same time it may result in confusion and errors.
Caching is the process of storing files in cache or temporary storage so that they can be retrieved quickly.
There are many types of caching like API caching, Query Caching, CDN cache, etc.. We are going to work on the simplest form of caching today that is client-side static content caching.
Caching helps to reduce the server load and reduce the response time but at the same time, it may show stale data to the user (๑•﹏•).
Instead of explaining let me show you the results
Network Tab Before Caching

Before Caching
Network Tab After Caching

After Caching

As you can see from the two images above heavy.jpg took 279 ms to load and style.css took 3 ms to load before caching but after caching both took 0 ms.

Isn't it great, the client never has to make the call to the server for content because it has your entire website in the cache? No, it's not, suppose you make some changes in style.css client will never know about the changes.

Tips for caching.

  • Never cache your main HTML page ( index.html ): Because if you cache your HTML page then you are kind of disconnected from the client. The client will never make calls to the server until the cache expires.
  • Use query Params in all links: Attach version number in all links like
    <link rel="stylesheet" href="/path/style.css?v=1">
    ?v=1 specify the version number. You can always come back and increment the version number whenever you made some changes in style.css, the browser will consider this as a new entity.
  • Cache only static content: Cache contents that are frequently used like images. Don't try to cache dynamic content like API calls.

Implementing Caching in NODE.JS

You can get the code from here
Folder Structure For Implementing Caching Project

Folder Structure looks like this.
Index.js Page in Implementing Caching Project

Actual code

I've created two static directories public and cache. Whatever you put in the cache folder will be cached by the browser.
To set cache-control headers I've created a middleware in line 7.

Development with the cache.

Just a quick tip in case you don't know. You can disable the cache in chrome by following steps.
  • Open Chrome browser console
  • Navigate to the Network tab.
  • Click on Disable Cache
Disable Caching In Chrome