Search code examples
reactjscachingdeploymentcreate-react-appreact-scripts

Trigger hard cache refresh when index.html changes in create-react-app deployment


I'm currently building and deploying my create-react-app site using "react-scripts build", and then copying the contents of the build directory to an apache web directory. The web directory contains an index.html file, which points to the compiled React js file via a script tag like this:

<script type="text/javascript" src="/static/js/main.dd92ea42.js"></script>

That's all the built-in behavior of "react-script build". What I'm finding is that even though a new index.html file is created, and it has content changes (the path to that .js file changes with each deployment), the browser still caches the whole application. Even doing a "hard" refresh of the site doesn't load the new content. I have to fully delete the cache and then reload for anything to refresh.

Is there some trick to caching with create-react-app and building via react-scripts? I assume that the browser only looks at the index.html file if it doesn't have the app cached, and never looks at it again? Otherwise I don't understand why it doesn't see the changes to the index.html file when I redeploy.

So, what's the trick to deploying a create-react-app app, such that each deployment invalidates the browser's cache, and users don't need to go through hoops to get the new version?


Solution

  • It depends how your deployment pipeline is setup. There could be caching at several layers:

    • If you use a CDN it may be cached there.
    • As in your comments, the service worker could be caching it.
    • Depending how your Apache server is configured it probably won't "hot swap" new files and load them into memory. For me, I deploy to a nginx web server which needs to be restarted for it to reload new files into memory.
    • Sounds like you already made sure the browser isn't caching via a hard refresh.

    Lastly, I'm not quite sure how you're pointing to a hardcoded main.[xxxyyyzz].js file since the hash fragment changes if the underline source files have changed.