How can I ensure clients don't get stale static assets when the site is behind a CDN?

  • Page Owner: Not Set
  • Last Reviewed: 2020-05-26

I have an Episerver site behind a CDN. I update my static CSS / JS files, the CDN continues to serve the cached, old versions for some time. I can manually clear the CDN cache, but how can I do this in a more automated way and ensure clients always get the latest version of these files?


Additional Posts

A quick-and-dirty way is to append a query string parameter that changes every time the site is deployed. This isn't ideal, because not every deployment changes the static files, but is a decent trade-off between efficiency and complexity.

Here's an example that generates a GUID and remembers it until the next deployment:

    public static class ClientCache
    {
        public static readonly string CacheBuster = Regex.Replace(Convert.ToBase64String(Guid.NewGuid().ToByteArray()), "[/+=]", "");
    }

Then reference your files with a querystring parameter:

<script src="/statis/js/main.min.js?v=@ClientCache.CacheBuster"></script>

Because the URL has changed, both the CDN and the client are guaranteed to get the new version of the file.


System.Web.Optimization is dead. Avoid using it.

Note: We also have used System.Web.Optimization, but there are a couple important caveats to keep in mind:

  1. It behaves differently in debug mode, which means sometimes issues (particularly with paths and CSS variables) only appear in production--not an ideal place to find issues.
  2. If the bundling fails, it sometimes shows a YSOD for the entire page, not just the bundled assets.