Simple cache busting with Webpack

Josh Sherman
2 min read
Software Development DevOps

Here at CrowdSync, we’re huge fans of CloudFlare.

As customers, we are leveraging the power of CloudFlare’s caching mechanisms. Part of our deployment process to production involving flushing the cache via the CloudFlare API. Problem there is that only solves half of the caching dilemma.

Even with our CloudFlare cache being purged, modern browsers have their own caching mechanisms that also need to be busted.

To accomplish this, we channeled a concept from days of yore… versioning!

We could have went the route of appending a time stamp as a query string parameter of the bundled files, but I’ve never been a fan of how that looked. Doesn’t hurt that back in the day this method wasn’t as reliable as it is now.

Instead of a query string parameter, we have setup Webpack to inject the current time stamp into the file names being generated at the time the build was initiated.

No special plugins needed, just update your Webpack configuration to grab the current time stamp from the Date object and inject it into your file names:

// Default names for local development
const filenames = {
  css: 'bundle.css',
  js: 'bundle.js',
};

// Cache busted names for production
if (process.env.NODE_ENV === 'production') {
  const timestamp = +new Date();

  filenames.css = `bundle.${timestamp}.css`;
  filenames.js = `bundle.${timestamp}.js`;
}

Then you can update any file name references you’re making to use the filenames variable. Include additional variables or removes the ones you don’t need, your call.

With the way we deploy our web application to production, this method gives us the added benefit of having our bundle files versioned and we could easily roll back if necessary.

Eventually we’ll need to starting pruning the bundle files in production, but no need for premature optimization at this point in the game.

We can save that for tomorrow… NEXT ISSUE!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles