Angular rookie mistakes — How to cache bust an Angular 2+ application in production

Krishnan Mudaliar
Oct 8, 2018 · 2 min read

Typical Problems

“Angular app changes are not getting reflected on production.”

“Angular app is not loading ANYTHING on production after a new release.”

“My Angular app is always loading the older app files unless I clear my browser cache.”

For another example, in the most recent release, you changed the API end-point URL for fetching the logged in user’s information. The new app has those changes, all tested and great, but the support team has been receiving complaints ever since the new release that the app is not working at all. You figure out that almost all such complaints are from users who logged in to the app in the recent past.

Cause

The issue is quite simple: Browser cache. The client browser has also cached the app’s index.html file along with other static resource files, like images, CSS and JS files. However, caching index.html means that the <script src="hashed-app-bundles.js"> inside it are also old, i.e. still pointing to the old JS and CSS files. Hence the issue.

Solution

You have to set Cache-Control headers on index.html file before it is served. This informs the browser to ALWAYS request for index.html from the server and never cache it locally.

Cache-Control: no-cache, no-store

If you are a web developer, you must be knowing at least one technique to set Http Headers in the language of expertise. Setting HTTP cache headers on static files, however, are typically (but not limited to) done by web servers or dynamic/proxy request handlers. For example, on IIS-hosted applications, you can do this by adding the following to your web.config file.

<location path="index.html">
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Cache-Control" value="no-cache, no-store" />
</customHeaders>
</httpProtocol>
</system.webServer>
</location>

Unfortunately, for users who already opened the app recently, there is no direct way out but to ask them to “clear your browser cache”. You could try hack your way through this problem for these users, but that is out of scope of this article. Maybe I can try covering that in a different post if people are really interested in it.

TIP: Before you ask them to clear their browser cache, try to have the Cache-Control headers fix on production already. Else, the user, even after clearing his/her browser cache, will now have cached the newer version of the app that will again cause issues after the next release.