2

I have created an app using create-react-app, which is deployed using heroku. I have replaced the serviceWorker.ubregister(); to serviceWorker.register();. Service worker works fine when I followed the the below steps from https://facebook.github.io/create-react-app/docs/deployment

npm i -g serve
serve -s build -l 4000

I am assuming something to do with the process.env.PUBLIC_URL but not sure how to fix this.

Code can be found: https://github.com/subhendukundu/gif-code-snippet Hosted in: https://gif-code-snippet.herokuapp.com/

Subhendu Kundu
  • 3,618
  • 6
  • 26
  • 57
  • 1
    I hope you have used the correct buildpack also? `heroku buildpacks:set https://github.com/mars/create-react-app-buildpack.git#v1.2.1`? – Tarun Lalwani Jul 16 '19 at 07:37

1 Answers1

0

Yeah! I don't know I too had the same problem of ServiceWorker registration during my development of a PWA.

I think there is an issue with the serviceWorker.js file that comes with create-react-app. So I had a custom serviceWorker.js which was more development friendly with logs on console showing the corresponding events of the ServiceWorker. I found the below register() function as useful.

export default function register() {
  if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) {
    // The URL constructor is available in all browsers that support SW.
    const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
    if (publicUrl.origin !== window.location.origin) {
      // Our service worker won't work if PUBLIC_URL is on a different origin
      // from what our page is served on. This might happen if a CDN is used to
      // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
      return;
}

Though window.location and window.location.href are both synonymous. I prefer former as process.env.PUBLIC_URL by default is a path and not an URL.

However I recommend you to replace your serviceWorker.js file with this file.

Abhinav Kinagi
  • 3,653
  • 2
  • 27
  • 43