'Service worker register then - Undefined is not a function

I use default React code for registering service worker. I have reports in bugsnag that some users are getting TypeError: undefined is not a function on the line .then(registration => { inside registerValidSW.

For me it is working but for some probably not. I did not find where could be a problem.

Could you help me with this?

export function register() {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
  return;
}

window.addEventListener('load', () => {
  const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

  if (isLocalhost) {
    .......
  } else {
    registerValidSW(swUrl);
  }
});
}
}

function registerValidSW(swUrl) {
 navigator.serviceWorker
.register(swUrl)
.then(registration => {
  registration.onupdatefound = () => {
    const installingWorker = registration.installing;
    if (installingWorker == null) {
      return;
    }
    installingWorker.onstatechange = () => {
      ...
    };
  };
})
.catch(error => {
  console.error('Error during service worker registration:', error);
});
}


Solution 1:[1]

Serviceworker and its methods including register are supported on all latest browsers excluding IE.

It has been noticed that even when serviceWorker is accessible in navigator, property register is not present which should always return a promise. Chromium bug for the same.

For now, you could avoid this issue by adding the following check:

'serviceWorker' in navigator && 'register' in navigator.serviceWorker

Solution 2:[2]

This is happening because you are using normal react app template which does not have service worker functions like register()

to use pwa react app create your react app by

npx create-react-app my-app --template cra-template-pwa

TypeScript equivalent

npx create-react-app my-app --template cra-template-pwa-typescript

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mappie
Solution 2 Dewansh Thakur