create-react-appbrowser-cache

Create React App and CSS caching in production


I have a medium size React app created using Create React App (it has a .NET backend). When I run it locally there are no problems with caching - I make a change in CSS and I instantly see the change in the browser. But when I deploy the app to an Azure App Service users don't see any of the style changes, untill they press the "Empty Cache and Hard Reload" button. My users are not technical at all and struggle with it - is there a way to force refresh when a new version of the app is deployed.

I thought maybe adding hashes to the CSS filenames in production will solve this, but it looks like this will require ejecting the app and I'm not sure it will work.


Solution

  • If you name your css files with versions it will automatically cause the website to "properly" reload as it will require a file that wasnt previously fetched. For example:

    old version uses my_site_1.css new version uses my_site_2.css

    The browser will request the new file and it wont be cached therefore fetching the new one.

    Making a variation of this to save work you can make the query with a random query param causing it to load every time, this will have a rare edge case where the same number will come out twice

    will look as so:

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Dynamic CSS Version</title>
        <script>
            function loadStylesheet() {
                var link = document.createElement('link');
                link.rel = 'stylesheet';
                link.type = 'text/css';
                link.href = '/css/stylesheet.css?v=' + Math.random();
                document.head.appendChild(link);
            }
    
            loadStylesheet();
        </script>
    </head>
    

    Alternatively you can try to clear the localstorage

    if your website is deployed via iss you can edit it as such

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
        <system.webServer>
            <caching enabled="false" enableKernelCache="false" />
        </system.webServer>
    </configuration>
    

    if you are hosting it in a different way it probably has a similar option