Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Service Worker weird caching #5316

Open
gabrielmicko opened this issue Oct 5, 2018 · 71 comments
Open

Service Worker weird caching #5316

gabrielmicko opened this issue Oct 5, 2018 · 71 comments

Comments

@gabrielmicko
Copy link

gabrielmicko commented Oct 5, 2018

Is this a bug report?

Yes

Did you try recovering your dependencies?

Yes

Which terms did you search for in User Guide?

#2398

Environment

Environment Info:

System:
OS: macOS High Sierra 10.13.6
CPU: x64 Intel(R) Core(TM) i5-5257U CPU @ 2.70GHz
Binaries:
Node: 9.10.0 - /usr/local/bin/node
Yarn: 1.10.1 - /usr/local/bin/yarn
npm: 5.6.0 - /usr/local/bin/npm
Browsers:
Chrome: 69.0.3497.100
Firefox: 62.0.3
Safari: 12.0
npmPackages:
react: ^16.5.2 => 16.5.2
react-dom: ^16.5.2 => 16.5.2
react-scripts: 2.0.4 => 2.0.4
npmGlobalPackages:
create-react-app: 2.0.3

Steps to Reproduce

(Write your steps here:)

  1. Clone https://github.com/gabrielmicko/react-create-app-pwa. It is almost a clean app of react-create-app.
  2. Install dependencies. yarn install. Create a build. yarn run build.
  3. Run serve -s build (if you don't have serve yarn global add serve), or node server.js.
  4. Open localhost:5000. You should see service worker precaching files.
  5. Do some change in the App.js and run yarn run build again.
  6. Refresh the page and check your console. You should see the new files. It will log an "Update happened" message.
  7. Refresh the page to see the updates.
  8. Can't see the changes I made.

Expected Behavior

After refreshing the page at point 7. I should see my changes.

Actual Behavior

I see the old version of my app.

(Write what happened. Please add screenshots!)

Reproducible Demo

https://www.youtube.com/watch?v=Hl5HbZ0TWoY

@Timer
Copy link
Contributor

Timer commented Oct 5, 2018

You need to close all tabs or fully close the browser to see the changes reflected. A page reload will not reflect the changes.

@Timer Timer closed this as completed Oct 5, 2018
@FezVrasta
Copy link
Contributor

FezVrasta commented Oct 5, 2018

Hey @Timer, from what I see on the video, OP is using the incognito mode with a single open tab.

I cloned the repo and I can reproduce the problem as well. Maybe something is wrong with the V2 service worker?

@Timer
Copy link
Contributor

Timer commented Oct 5, 2018

/cc @jeffposnick

@Timer Timer reopened this Oct 5, 2018
@gabrielmicko
Copy link
Author

Is this the expected behaviour? Does it happen only on localhost? When onUpdate gets called I would like to add a popup which prompts the user to reload the page.

@Timer
Copy link
Contributor

Timer commented Oct 5, 2018

Yes -- the expected behavior is that you must close all tabs or browser before the new content appears. This is the behavior everywhere, not just on localhost.

You should be able to override this via ServiceWorkerGlobalScope.skipWaiting() but you need to make sure you coordinate this across all instances of your apps running in their browser.

@FezVrasta
Copy link
Contributor

May we convert this into a "doc improvement" issue so that we keep track of this? I think the current documentation should at least mention it.

@Timer
Copy link
Contributor

Timer commented Oct 5, 2018

@gabrielmicko
Copy link
Author

gabrielmicko commented Oct 5, 2018

In the meantime I found this: https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin skipWaiting: true does the job.

@jeffposnick
Copy link
Contributor

Yes, this does warrant improvements to the v2 docs. I can tackle that next week.

FYI, #3613 (comment) is the best explanation of why defaulting skipWaiting to false was the safest thing to do for c-r-a v2.

tl;dr is that if skipWaiting is true and you lazy-load resources, there's a decent chance that you might end up trying to lazy-load a URL that no longer exists in the service worker's cache or on the server. If you don't lazy-load versioned URLs and you want the old behavior, then changing your config to using skipWaiting: true is the alternative.

@mymattcarroll
Copy link

@gabrielmicko , @jeffposnick , Can the skipWaiting: true option be applied without ejecting?

@mymattcarroll
Copy link

mymattcarroll commented Oct 6, 2018

On this line the workbox-webpack-plugin is registered with clientsClaim: true and the documentation for workbox-webpack-plugin's skipWaiting option says

Whether or not the service worker should skip over the waiting lifecycle stage. Normally this is used with clientsClaim: true.

Should the default behaviour be setting clientsClaim: true and skipWaiting: true?

@gabrielmicko
Copy link
Author

@mymattcarroll yes, that way you get the update asap. For now I don't know how am I going to get a callback about the update onUpdate seems to be broken if skipWaiting is set to true. I'll take a look later.
Also I don't know how I can add skipWaiting: true without hacking in the node_modules. Any idea?

@gabrielmicko
Copy link
Author

gabrielmicko commented Oct 6, 2018

Finally I was able to test with "react-scripts": "^1.1.0". Actually it works how it should!

serviceWorker.register({
   onUpdate:() => {
       //Some UI notification comes here, then reload
       window.location.reload();
    }
})

Once it reloads, I instantly see the change, whereas in create-react-app v2 I won't. I guess this is something that has to be addressed. Please at least make it configurable.
For example:

serviceWorker.register({
    skipWaiting: true
    onUpdate:() => {
});

This case onUpdate would instantly fire once skipWaiting() get's called.

What do you think?

/cc @jeffposnick

Edit: actually I am a little confused if it could be added to serviceWorker.js file. Cause I guess it has to be in the service-worker.js.

@mymattcarroll
Copy link

@gabrielmicko, it will have to be a build time configuration as it needs to be added to the webpack configuration here.

Perhaps configuration in package.json? The package.json is already being used for build time configuration using the browserlist property. Maybe something like:

{
  "serviceWorkerOptions": {
    "skipWaiting": true
  }
}

@gabrielmicko
Copy link
Author

gabrielmicko commented Oct 7, 2018

@mymattcarroll This would be awesome. Other questions is how do you let serviceWorker.js know that skipWaiting has been called? The developer want's to subscribe to that event, so he can let the users know there was an update.

@mymattcarroll
Copy link

mymattcarroll commented Oct 8, 2018

@Timer, it seems the default behaviour of the service worker has changed between v1 and v2. Our project is no longer hitting this line to allow us to prompt the user when new content is available by just refreshing the current page.

Was this intentional?

If it was, I have been able to make changes to a local fork to get v1 behaviour to occur again by making the following changes:

  1. Updating the serviceWorker.js check the event object passed to registration.installing.onstatechange instead of checking registration.installing.state (it seemed there was a race condition where multiple state changes were occurring so fast that registration.installing.state was always equal to 'activated')
  2. Updating webpack.config.prod.js to pass skipWaiting: true to workbox-webpack-plugin configuration

I would be happy to contribute with a pull request if you believe these changes are desirable for others.

If setting skipWaiting: true by default is not desirable, would you consider a configuration option, perhaps in package.json? I would be happy to work on making the UX similar to how the browserslist property is added to package.json with a prompt.

This library is awesome, would hate to consider ejecting...

@gabrielmicko
Copy link
Author

Very well said @mymattcarroll! This is what I realised as well! I guess the default behaviour should match v1 so that devs would not need to change anything!

@jeffposnick
Copy link
Contributor

So I had mistakenly thought that being able to override the default Workbox options via an external config file had made it into c-r-a v2 branch, but as per #5111 (comment) that was just a proposal and not actually something that landed.

That would allow folks who feel comfortable with the tradeoffs around potentially buggy lazy-loading to opt-in to using skipWaiting: true, and get a quicker update flow.

I've filed separate issue to track the addition of that config file: #5359

@frederikhors
Copy link

I'm in favor of adding a cra.config.js for these config and others, overriding default ones!

At first I thought it could already be done.

@andidev
Copy link

andidev commented Oct 10, 2018

@mymattcarroll

Can the skipWaiting: true option be applied without ejecting?

This is the hacky way I had to do it
install replace-in-file

npm install --save-dev replace-in-file

create a file in the root called hack-add-skipWaiting-true-to-react-script.js
UPDATE
Changed webpack-config.prod.js to webpack-config.js since the file is renamed in current version

'use strict';
const replace = require('replace-in-file');

try {
    console.log('Adding skipWaiting: true to react-script webpack-config.js');
    replace.sync({
        files: 'node_modules/react-scripts/config/webpack.config.js',
        from: /clientsClaim: true,$/gm,
        to: (match) => {
            return match + ' skipWaiting: true,';
        },
    });
} catch (e) {
    console.log('Something went wrong when trying to add skipWaiting: true to react-script webpack-config.js', e);
    process.exit();
}

Add it as a postinstall script to your package.json

{
   ...
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "postinstall": "node hack-add-skipWaiting-true-to-react-script.js"
  }
}

run npm install and skipWaiting should now be set to true

@mymattcarroll
Copy link

Very sneaky @andidev ;)

I have rolled back to react-scripts@1.1.5 for now in the hope #5369 gets accepted.

@gabrielmicko
Copy link
Author

If you use react-app-rewired it is fairly easy to achieve this. I can post it if somebody wants it.

@kevinOriginal
Copy link

If you use react-app-rewired it is fairly easy to achieve this. I can post it if somebody wants it.

That'd be good but isn't react-app-wired deprecated on CRA v2.0?

@FezVrasta
Copy link
Contributor

@kevinOriginal nope, the message on their repo is confusing. It works just fine, it's just that the utilities used to inject your own configuration work just on V1. But you can either write the code yourself or use the ones provided by customize-cra

@riccoski
Copy link

Thanks for the solutions. Works perfect for me on ios. I had to tweak obviously to get it working how I wanted.

@andrewBsk
Copy link

Thanks for the solutions. Works perfect for me on ios. I had to tweak obviously to get it working how I wanted.

Can you share tweaks please?
Still not able to make it work on iOS as a PWA neither as web app on Safari.

@riccoski
Copy link

riccoski commented Jul 4, 2019

Thanks for the solutions. Works perfect for me on ios. I had to tweak obviously to get it working how I wanted.

Can you share tweaks please?
Still not able to make it work on iOS as a PWA neither as web app on Safari.

I'd recommend posting what you have. And are you posting skip waiting on a button click?

@andrewBsk
Copy link

Thanks for the solutions. Works perfect for me on ios. I had to tweak obviously to get it working how I wanted.

Can you share tweaks please?
Still not able to make it work on iOS as a PWA neither as web app on Safari.

I'd recommend posting what you have. And are you posting skip waiting on a button click?

No, i just used the following snipped that was shared above.
Not sure how to trigger skip waiting on a button click i am afraid.

serviceWorker.register({
  onUpdate: registration => {
    const waitingServiceWorker = registration.waiting

    if (waitingServiceWorker) {
      waitingServiceWorker.addEventListener("statechange", event => {
        if (event.target.state === "activated") {
          window.location.reload()
        }
      });
      waitingServiceWorker.postMessage({ type: "SKIP_WAITING" });
    }
  }
});

@marlonmleite
Copy link

marlonmleite commented Jul 4, 2019

@andrewBsk

The problem of not updating the cache in iOS, I opened this issue for Safari (only PWA): https://bugs.webkit.org/show_bug.cgi?id=199110

While this problem is not solved, I did a workround that worked well for me: https://gist.github.com/kawazoe/fa3b5a3c998d16871ffb9e2fd721cb4b#gistcomment-2953706

@riccoski
Copy link

riccoski commented Jul 4, 2019

Thanks for the solutions. Works perfect for me on ios. I had to tweak obviously to get it working how I wanted.

Can you share tweaks please?
Still not able to make it work on iOS as a PWA neither as web app on Safari.

I'd recommend posting what you have. And are you posting skip waiting on a button click?

No, i just used the following snipped that was shared above.
Not sure how to trigger skip waiting on a button click i am afraid.

serviceWorker.register({
  onUpdate: registration => {
    const waitingServiceWorker = registration.waiting

    if (waitingServiceWorker) {
      waitingServiceWorker.addEventListener("statechange", event => {
        if (event.target.state === "activated") {
          window.location.reload()
        }
      });
      waitingServiceWorker.postMessage({ type: "SKIP_WAITING" });
    }
  }
});

And what's in your service-worker.js? as the above alone won't trigger the update.
The default service-worker.js doesnt have any params for the register function. So you'd need to change that.

and in the register & registerValidSW function you need to have props.onUpdate attached to an event that tells the worker theres an update.

Also without those it shouldn't work on chrome too? Or has it been working there for you?
Can use the chrome tab to debug
image

@andrewBsk
Copy link

alidSW function you need to have props.onUpdate attached to an event that tells the worker theres an update.

Also without those it shouldn't

Thanks for your response.
No, i haven't tried other browsers.
Service worker is the default generated by create-react-app, haven't changed anything there yet.
Feeling lost, is there a snippet available i can have a look maybe?

@andrewBsk
Copy link

andrewBsk commented Jul 4, 2019

On > > > > > Thanks for the solutions. Works perfect for me on ios. I had to tweak obviously to get it working how I wanted.

Can you share tweaks please?
Still not able to make it work on iOS as a PWA neither as web app on Safari.

I'd recommend posting what you have. And are you posting skip waiting on a button click?

No, i just used the following snipped that was shared above.
Not sure how to trigger skip waiting on a button click i am afraid.

serviceWorker.register({
  onUpdate: registration => {
    const waitingServiceWorker = registration.waiting

    if (waitingServiceWorker) {
      waitingServiceWorker.addEventListener("statechange", event => {
        if (event.target.state === "activated") {
          window.location.reload()
        }
      });
      waitingServiceWorker.postMessage({ type: "SKIP_WAITING" });
    }
  }
});

And what's in your service-worker.js? as the above alone won't trigger the update.
The default service-worker.js doesnt have any params for the register function. So you'd need to change that.

and in the register & registerValidSW function you need to have props.onUpdate attached to an event that tells the worker theres an update.

Also without those it shouldn't work on chrome too? Or has it been working there for you?
Can use the chrome tab to debug
image

I was able to make the update work following this guide but for chrome and Android only.
On iOS and safari I get the notification but service worker does not get updated
https://colmenerodigital.com/blog/implementing-pwa-update-notification/

@lebed2045
Copy link

Yes, this does warrant improvements to the v2 docs. I can tackle that next week.

FYI, #3613 (comment) is the best explanation of why defaulting skipWaiting to false was the safest thing to do for c-r-a v2.

tl;dr is that if skipWaiting is true and you lazy-load resources, there's a decent chance that you might end up trying to lazy-load a URL that no longer exists in the service worker's cache or on the server. If you don't lazy-load versioned URLs and you want the old behavior, then changing your config to using skipWaiting: true is the alternative.

this is precisely what had happened to me. On the smartphone app became dead and users can do nothing with that
Screen Shot 2019-08-17 at 6 56 49 PM
so index.html refer old chunks
Screen Shot 2019-08-17 at 7 32 52 PM
Does anyone know fix of that?

@lebed2045
Copy link

This is code I use:

/* eslint-disable */

// This optional code is used to register a service worker.
// register() is not called by default.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.

// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA

import Toaster from './services/Toaster';

const isLocalhost = Boolean(
  window.location.hostname === 'localhost' ||
    // [::1] is the IPv6 localhost address.
    window.location.hostname === '[::1]' ||
    // 127.0.0.1/8 is considered localhost for IPv4.
    window.location.hostname.match(
      /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
    )
);

export function register(config) {
  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.href);
    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/facebook/create-react-app/issues/2374
      return;
    }

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

      if (isLocalhost) {
        // This is running on localhost. Let's check if a service worker still exists or not.
        checkValidServiceWorker(swUrl, config);

        // Add some additional logging to localhost, pointing developers to the
        // service worker/PWA documentation.
        navigator.serviceWorker.ready.then(() => {
          console.log(
            'This web app is being served cache-first by a service ' +
              'worker. To learn more, visit https://bit.ly/CRA-PWA'
          );
        });
      } else {
        // Is not localhost. Just register service worker
        registerValidSW(swUrl, config);
      }
    });
  }
}

function registerValidSW(swUrl, config) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        if (installingWorker == null) {
          return;
        }
        installingWorker.onstatechange = () => {
          if (installingWorker.state === 'installed') {
            if (navigator.serviceWorker.controller) {
              // At this point, the updated precached content has been fetched,
              // but the previous service worker will still serve the older
              // content until all client tabs are closed.
              console.log(
                'New content is available and will be used when all ' +
                  'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
              );

              Toaster.show({
                message: 'New version available!',
                intent: 'success',
                action: {
                  onClick: () => {
                    installingWorker.postMessage({ action: 'skipWaiting' });
                    window.location.reload();
                  },
                  text: 'Update'
                }
              });

              // Execute callback
              if (config && config.onUpdate) {
                config.onUpdate(registration);
              }
            } else {
              // At this point, everything has been precached.
              // It's the perfect time to display a
              // "Content is cached for offline use." message.
              console.log('Content is cached for offline use.');

              // Execute callback
              if (config && config.onSuccess) {
                config.onSuccess(registration);
              }
            }
          }
        };
      };
    })
    .catch(error => {
      console.error('Error during service worker registration:', error);
    });
}

function checkValidServiceWorker(swUrl, config) {
  // Check if the service worker can be found. If it can't reload the page.
  fetch(swUrl)
    .then(response => {
      // Ensure service worker exists, and that we really are getting a JS file.
      const contentType = response.headers.get('content-type');
      if (
        response.status === 404 ||
        (contentType != null && contentType.indexOf('javascript') === -1)
      ) {
        // No service worker found. Probably a different app. Reload the page.
        navigator.serviceWorker.ready.then(registration => {
          registration.unregister().then(() => {
            window.location.reload();
          });
        });
      } else {
        // Service worker found. Proceed as normal.
        registerValidSW(swUrl, config);
      }
    })
    .catch(() => {
      console.log(
        'No internet connection found. App is running in offline mode.'
      );
    });
}

export function unregister() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.ready.then(registration => {
      registration.unregister();
    });
  }
}

@AnatoleLucet
Copy link

If anyone wonder, here is a TypeScript version of @EddiG's onUpdate :

serviceWorker.register({
  onUpdate: registration => {
    const waitingServiceWorker = registration.waiting;

    interface ServiceWorkerEvent extends Event {
      target: Partial<ServiceWorker> & EventTarget | null;
    }

    if (waitingServiceWorker) {
      waitingServiceWorker.addEventListener(
        'statechange',
        (event: ServiceWorkerEvent) => {
          if (event.target && event.target.state === 'activated') {
            window.location.reload();
          }
        }
      );
      waitingServiceWorker.postMessage({ type: 'SKIP_WAITING' });
    }
  }
});

It probably could be improved, but it seems to do the job.

@p4ul
Copy link

p4ul commented Oct 8, 2019

pro tip:
After lots of experimenting and using techniques mentioned above I have found this way to add a custom dialog that lets you ask the user if they want to update

in the bottom of your index file add

registerServiceWorker({
    onUpdate: async function (registration) {
            const waitingServiceWorker = registration.waiting
                const bc = new BroadcastChannel('app-update');
                bc.postMessage('App has updated.');
            }
        })

then add a component (make sure you render it somewhere)

import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import * as React from "react";
import withTheme from "./components/tmx/withTheme";

class ReleaseDialog extends React.Component {
    public state = {
        open: false,
    };

    public componentWillMount = () => {
        if (typeof BroadcastChannel !== 'undefined') {
            const updateChannel = new BroadcastChannel('app-update');
            updateChannel.addEventListener('message', event => {
                this.setState({open: true})
            });
        }
    }

    public handleAccept = async () => {
        try {
            if (navigator && navigator.serviceWorker) {
                const waitingServiceWorker = await navigator.serviceWorker.ready

                if (waitingServiceWorker.waiting) {
                    waitingServiceWorker.waiting.postMessage({type: "SKIP_WAITING"});
                }
            }
        } catch (e) {
            console.error(e)
        }
    }

    public handleClose = () => {
        this.setState({open: false});
    };

    public render() {
        const {version} = this.props;
        return (
            <div>
                <Dialog
                    open={this.state.open}
                    onClose={this.handleClose}
                >
                    <DialogTitle id="alert-dialog-title">The site Just got better!</DialogTitle>
                    <DialogActions>
                        <Button onClick={this.handleClose} color="default">
Cancel
                        </Button>
                        <Button onClick={this.handleAccept} color="primary" autoFocus={true}>
                            UPDATE
                        </Button>
                    </DialogActions>
                </Dialog>
            </div>

        )
    }
}

also add this just before the closing tag of
function registerValidSW(swUrl, config) {
inside registerServiceWorker.js

   let refreshing = false;

    navigator.serviceWorker.addEventListener('controllerchange', () => {
        if (refreshing) {
            return;
        }

        refreshing = true;
        console.log("controller change")
        window.location.reload();
    });

The most important thing to note is you need to send SKIP_WAITING to the waiting serviceWorker not the active one!

PS I stripped out/altered some stuff from the code above so it may need to be altered

@andriijas andriijas added this to the 4.0 milestone Oct 30, 2019
@ifier
Copy link

ifier commented Oct 31, 2019

There are a lot of solutions. Do we have one universal solution to solve this issue without custom webpack config, workbox and etc.?
Can create-react-app solve this issue out of the box? I think it's major question!

@riccoski
Copy link

riccoski commented Oct 31, 2019 via email

@adjieindrawan
Copy link

@sky93 With CRA v3 you can post a message SKIP_WAITING to the service worker to trigger skip waiting.

// index.js
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";

ReactDOM.render(<App />, document.getElementById("root"));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.register({
  onUpdate: registration => {
    const waitingServiceWorker = registration.waiting

    if (waitingServiceWorker) {
      waitingServiceWorker.addEventListener("statechange", event => {
        if (event.target.state === "activated") {
          window.location.reload()
        }
      });
      waitingServiceWorker.postMessage({ type: "SKIP_WAITING" });
    }
  }
});

But usualy you want ot ask user before doing reload. I used wrapping service worker registration into the React context:

import React from "react";
import * as serviceWorker from "./serviceWorker";

const ServiceWorkerContext = React.createContext();

function ServiceWorkerProvider(props) {
  const [waitingServiceWorker, setWaitingServiceWorker] = React.useState(null);
  const [assetsUpdateReady, setAssetsUpdateReady] = React.useState(false);
  const [assetsCached, setAssetsCached] = React.useState(false);

  const value = React.useMemo(
    () => ({
      assetsUpdateReady,
      assetsCached,
      // Call when the user confirm update of application and reload page
      updateAssets: () => {
        if (waitingServiceWorker) {
          waitingServiceWorker.addEventListener("statechange", event => {
            if (event.target.state === "activated") {
              window.location.reload()
            }
          });

          waitingServiceWorker.postMessage({ type: "SKIP_WAITING" });
        }
      }
    }),
    [assetsUpdateReady, assetsCached, waitingServiceWorker]
  );

  // Once on component mounted subscribe to Update and Succes events in 
  // CRA's service worker wrapper
  React.useEffect(() => {
    serviceWorker.register({
      onUpdate: registration => {
        setWaitingServiceWorker(registration.waiting);
        setAssetsUpdateReady(true);
      },
      onSuccess: () => {
        setAssetsCached(true);
      }
    });
  }, []);

  return <ServiceWorkerContext.Provider value={value} {...props} />;
}

function useServiceWorker() {
  const context = React.useContext(ServiceWorkerContext);

  if (!context) {
    throw new Error(
      "useServiceWorker must be used within a ServiceWorkerProvider"
    );
  }

  return context;
}

export { ServiceWorkerProvider, useServiceWorker };

The only additional change required in the serviceWorker.js file of CRA if you want to register service worker from the React application. You need to get rid of the window.onload event waiting in the register function :

// serviceWorker.js
export function register(config) {
  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.href);
    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/facebook/create-react-app/issues/2374
      return;
    }

    // We are not waiting for window's load event as it was for the create-react-app template
    // because we register a service worker in the React app that runs after window loaded
    // and the load event already was emitted.
    const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

    if (isLocalhost) {
      // This is running on localhost. Let's check if a service worker still exists or not.
      checkValidServiceWorker(swUrl, config);

      // Add some additional logging to localhost, pointing developers to the
      // service worker/PWA documentation.
      navigator.serviceWorker.ready.then(() => {
        console.log(
          "This web app is being served cache-first by a service " +
            "worker. To learn more, visit http://bit.ly/CRA-PWA"
        );
      });
    } else {
      // Is not localhost. Just register service worker
      registerValidSW(swUrl, config);
    }
  }
}

Thanks!

@baptisteArno
Copy link

I don't understand why it's advised to ask the user to update the app before triggering skipWaiting(). This piece of code just tells the browser to replace the old service worker with the new one and on the next refresh, new version will be installed right ?

serviceWorker.register({
  onUpdate: (registration: ServiceWorkerRegistration) => {
    if (registration.waiting) {
      registration.waiting.postMessage({ type: "SKIP_WAITING" });
    }
  }
});

@ifier
Copy link

ifier commented Nov 22, 2019

I don't understand why it's advised to ask the user to update the app before triggering skipWaiting(). This piece of code just tells the browser to replace the old service worker with the new one and on the next refresh, new version will be installed right ?

serviceWorker.register({
  onUpdate: (registration: ServiceWorkerRegistration) => {
    if (registration.waiting) {
      registration.waiting.postMessage({ type: "SKIP_WAITING" });
    }
  }
});

Yes. You are right. And you can force refresh a page.

@riccoski
Copy link

riccoski commented Nov 22, 2019 via email

@baptisteArno
Copy link

I don't understand why it's advised to ask the user to update the app before triggering skipWaiting(). This piece of code just tells the browser to replace the old service worker with the new one and on the next refresh, new version will be installed right ?

serviceWorker.register({
  onUpdate: (registration: ServiceWorkerRegistration) => {
    if (registration.waiting) {
      registration.waiting.postMessage({ type: "SKIP_WAITING" });
    }
  }
});

Ok I have an issue with this solution. whenever I refresh a lot, in a small period of time, when I know there's a new update available, it will skip the update and it will stay in a "waiting to activate" state ... Any chance I can trigger the update when it's in this state ?

@baptisteArno
Copy link

Ok, to make sure skipWaiting() is called whenever a new service worker is in a waiting state (ready to replace the old one), you need to have this setup:

index.js:

serviceWorker.register({
  onUpdate: (registration: ServiceWorkerRegistration) => {
    if (registration.waiting) {
      registration.waiting.postMessage({ type: "SKIP_WAITING" });
    }
  }
});

serviceWorker.js:

function registerValidSW(swUrl: string, config?: Config) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        [...]
      };
      if (registration.waiting && config && config.onUpdate) {
        config.onUpdate(registration);
      }
    })
}

@jfbloom22
Copy link

jfbloom22 commented Feb 17, 2020

I ran into the same issue with users struggling to load the updated version of my app. I read through this thread and came up with a simplified solution thanks to the updates that have been made to the serviceWorker.js included in CRA 3.2.0. Note that this solution only works well if you are Not lazy-loading.

in index.tsx add:

  serviceWorker.register({
    onUpdate: registration => {
    alert('New version available!  Ready to update?');
    window.location.reload();
      if (registration && registration.waiting) {
        registration.waiting.postMessage({ type: 'SKIP_WAITING' });
      }
    }
  });

I wrote a blog post that explains more here: https://steemit.com/typescript/@jfbloom22/how-to-handle-upgrades-with-service-workers-with-cra3-and-typescript

@estevaolucas
Copy link

estevaolucas commented Feb 25, 2020

serviceWorker.register({
  onUpdate: async registration => {
    // We want to run this code only if we detect a new service worker is
    // waiting to be activated.
    // Details about it: https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle
    if (registration && registration.waiting) {
      await registration.unregister();
      // Makes Workbox call skipWaiting()
      registration.waiting.postMessage({ type: 'SKIP_WAITING' });
      // Once the service worker is unregistered, we can reload the page to let
      // the browser download a fresh copy of our app (invalidating the cache)
      window.location.reload();
    }
  },
});

@alanrubin
Copy link

Just to add to this thread and make it useful for more people, in my case my PWA is going to run for a long time without a refresh (a long-running always open dashboard in a TV, no end-user interactions). In this case, I understand I to need to trigger periodically check for updates by myself. A change needs to be done inside serviceWorker.ts file for that:

navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      // Start addition---
      // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#manual_updates
      // Added code, as our application will be open for a long time and we are a SPA, we need
      //  to trigger checks for updates frequently
      setInterval(() => {
        console.log('Checking if service worker was updated in server')
        registration.update()
      }, 15 * 60 * 1000) // Every 15 mins check
     // End addition---

      registration.onupdatefound = () => {...}

Hope that is useful and feel free to correct me if I'm wrong.

@iansu iansu removed this from the 4.0 milestone Aug 5, 2020
@Wynston
Copy link

Wynston commented Oct 8, 2020

Can anyone confirm if iOS 14 helps with these issues?

@dfyz011
Copy link

dfyz011 commented May 17, 2022

Hi, I can't decide which variant is better?
inspired by @sky93

serviceWorkerRegistration.register({
  onUpdate: async (registration) => {
    // We want to run this code only if we detect a new service worker is
    // waiting to be activated.
    // Details about it: https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle
    if (registration?.waiting) {
      await registration.unregister();
      registration.waiting.addEventListener('statechange', (event) => {
        const sw = event?.target as ServiceWorker;
        if (sw.state === 'activated') {
          // Once the service worker is unregistered, we can reload the page to let
          // the browser download a fresh copy of our app (invalidating the cache)
          window.location.reload();
        }
      });
      // Makes Workbox call skipWaiting() that will trigger upper listener
      registration.waiting.postMessage({ type: 'SKIP_WAITING' });
    }
  },
});

or by @estevaolucas

serviceWorkerRegistration.register({
  onUpdate: async (registration) => {
    // We want to run this code only if we detect a new service worker is
    // waiting to be activated.
    // Details about it: https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle
    if (registration?.waiting) {
      await registration.unregister();
      // Makes Workbox call skipWaiting()
      registration.waiting.postMessage({ type: 'SKIP_WAITING' });
      // Once the service worker is unregistered, we can reload the page to let
      // the browser download a fresh copy of our app (invalidating the cache)
      window.location.reload();
    }
  },
});

Also I want to know why should we call registration.unregister()?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests