Updating serviceworker in React App - successfully updates - but on refresh shows old code still with new serviceworker?

Viewed 253

I'm trying to show the newest updates to my app when there is an update available.

The react app is a create-react-app and its hosted on S3 and uses AWS cloudfront for caching.

When I push updates the client doesn't see those updates unless they do a hard refresh, so I looked into updating the serviceworker.

First:

Cloudfront is set to cache time of 0. So it should not display any old code.

The headers in index.html

  <meta http-equiv="cache-control" content="max-age=0" />

I have registered the serviceworker in index.js on loading of the app and pass in a config to update the serviceworker if there are new changes:

import swConfig from "./swConfig";


serviceWorker.register(swConfig);

swConfig.js

export default {
  onUpdate: (registration) => {
    registration.waiting.postMessage("skipWaiting");
    registration.unregister().then(() => {
      let confirm = window.confirm(
        "New updates to the app - please close the tab and reload"
      );
      if (confirm) {
        window.location.reload(true);
      } else {
        alert("Please close this tab and reload the page");
        window.location.reload(true);
      }
    });
  },
  onSuccess: (registration) => {
    console.info("sw on success state");
  },
};

What happens when there is a new update pushed to S3 and cloudfront is invalidated:

  1. User sees an alert to update the app.

  2. App refreshes.

  3. User sees NEW content on the homepage.

  4. If user refreshes - they see the OLD content again (or if they come back to the page at a later point in time, even after closing the tabs)

What is causing the old content to be displayed?

I have a feeling its related to "skipWaiting".

If I remove registration.waiting.postMessage("skipWaiting"); then the page will refresh and the serviceworker will update - but the user WON'T see the NEW content

0 Answers
Related