Search code examples
javascriptreactjsprogressive-web-appsservice-worker

Update PWA application (react)


I've got a PWA application that was created with create-react-app.

How to update my PWA application to get the latest change on the server, not from its caches?

I'm using react version +17 and using serviceWorker to create a PWA application with this CRA.


Solution

  • You can update installed PWA apps by uninstalling and re-install them to get the latest changes.

    But if you are familiar with the ServiceWorker on your CRA application, you can easily extend your service worker to update your application on every loading or any manual criteria.

    open your service worker registration file and find registerValidSW function on it. add this line:

    function registerValidSW(swUrl, config) {
      navigator.serviceWorker
        .register(swUrl)
        .then((registration) => {
    
          registration.update();        // <--------------- add this line ----
    
          registration.onupdatefound = () => {
            const installingWorker = registration.installing;
            if (installingWorker == null) {
              return;
            }
          }
        })
    }
    
    

    you can add an interval to update your application on period.

          // to update application on startup load
          registration.update();
    
          // create interval to update every 5 minutes
          setInterval(() => {
            registration.update();
            console.debug('Checked for update...');
          }, 1000 * 60 * 5);   // <--- this will update your application after 5 minutes.