Yet another cache buster module. It consists of two parts:
bustfunction that you use from your views to append a checksum parameter to your client side resources.
validateChecksumMiddlewarethat verifies incoming checksums and, if it does not match the file's actual checksum, overwrites the
Cache-Controlheader so that the file is not cached.
When this particular situation happens it is very important to not serve these resources with long lived cache headers since this will pollute the CDN with client side resources of the wrong version. We could simply respond with a
404 in this situation but we prefer to actually serve the wrong resource version so that the user can at least see the site. On the next page navigation the user will most likely get the correct version.
npm install exp-cachebuster --save
Where you setup your express application:
var express = ;var app = ;var cacheBuster = "public/css" "public/js";// Expose bust function to viewsapplocalsbust = cacheBusterbust;// Setup the checksum validation middlewarevar validateChecksum = cacheBuster;app;app;
In a view you might use the bust function like this:
link(rel="stylesheet", href="/css/" + bust("main.css"))
See https://github.com/ExpressenAB/exp-cachebuster/tree/master/test/example-app for a complete example application.
You can pre-calculate checksum for all resources via the warm-up function. This means that the cache will be ready before the view starts getting client requests and prevent potential cache misses.
var cacheBuster = "public/css" "public/js";cacheBuster;
Usage during development
By default file checksums will be caches in memory since files are not expected to change during the lifetime of the started application. During development however you just want to reload the page and pick up any changes. The cache buster has the flag
useCachedChecksums for this purpose.
The following snippet will make sure the file checksum is always calculated when bust is called if
NODE_ENV is set to
var cacheBuster = "public/css" "public/js" processenvNODE_ENV !== "development";
A advantage of using a cache buster during development is that any change to a client side resource will result in a new checksum which will lead to the browser fetching the new version.
Note that view or fragment caching can result in getting old client side resources. These should be disabled during development for the HTML that contains references to scripts, stylesheets etc.