Search code examples
javascriptreactjsservice-workercreate-react-app

Service Worker Cached Script tries to load old data


In my project I load json files asynchronously via import().then.

Occasionally, when new content is available but isn't applied yet, the old cached script bundle tries to load the json files by their old name (because the bundling generates new hash names on every build). But those files are not available anymore.

I saw that many apps use a toast message to inform their users about the update so they can refresh, but is there another way to solve this issue?


Solution

  • No. There's no automatic way to handle this.

    Based on your question I take it your SW configuration uses a cache-first strategy. Since it's a cache-first strategy the situation you described can happen and will happen sometimes.

    You have two options:

    1. Precache all the JSON files too. This way, when the old JS code tries to fetch the JS files asynchronously, they will be served from the SW's cache instead of going to the network. Client gets an old version of the whole app, including JSON files.

    2. Implement some sort of complex(ish) custom-logic that tries to get the files and in an error situation talks to your server, fetches the correct filenames, and tries again with the new filenames. You could easily generate a file that lists all the current JSON filenames.

    Both options have different gotchas and they might or might not work depending on the application.