When I try to register a service worker file in react app it will give me a reference error: navigator is not defined

Viewed 301
export default function swDev() {
    let swUrl = `${process.env.PUBLIC_URL}/sw.js`
    if('serviceWorker' in navigator) {
        navigator.serviceWorker.register(swUrl).then((res) => {
            console.warn("response", res)
        }).catch((err) => {
            console.warn("error is: ", err)
        })
    } else {
        console.log("service worker is not supported")
    } 
}

this is the following code I have also called this function in index.js file in my react app. Also created a simple sw.js file with a message that file is attached.

1 Answers

You should as well check if window is defined. The service worker should only be initialized client side

(typeof window != 'undefined' && window.document);
Related