Search code examples
reactjswebnext.jscaddy

A website is not refreshing because of caching of service worker, after switching from React to Next.js. How to force update?


A website made on react had a service worker for caching. We ran the website with unregister() code and the website was ported to Next.js . Although on some machines, the unregister code never ran, so now those machines are running the old react code and not reflecting any changes made and pushed to the server. The changes are running on incognito and other machines where the unregister code ran. It is on Caddy server.

How can I force it to refresh from server side? We can clear cache or unregister the service worker on our machine but we don't know how many clients have the old code.

Thanks!


Solution

  • So the issue has been solved. Made a new service worker file, with just the code to remove the service worker.

    if ("serviceWorker" in navigator) {
      window.addEventListener("load", function () {
        navigator.serviceWorker.getRegistrations().then((registrations) 
    => {
          for (let registration of registrations) {
           registration.unregister().then((bool) => {
              console.log("unregister: ", bool);
            });
         }
        });
      });
    }
    

    And put this file in the exact location where the previous service worker was kept (You can find this out from the chrome developer tools). Also include the script tag linking this file in index.html or _document.js (for next.js). This should resolve the issue.