Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are a few steps you can take to ensure that your create-react-app will reload when the service worker is updated:

  1. When you start your development server, make sure to disable the service worker by setting the skipWaiting and clientsClaim options to false. You can do this by modifying your serviceWorker.js file:
// serviceWorker.js
register(null, {
  skipWaiting: false,
  clientsClaim: false,
});
  1. In your index.js file, add a listener to wait for the service worker to register:
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

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

// Wait for service worker to register
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/service-worker.js').then(registration => {
      console.log('Service worker registered:', registration);

      // Force reload when new service worker becomes active
      registration.addEventListener('updatefound', () => {
        console.log('New service worker found!');

        // If a new service worker is found, wait until it becomes active, then reload the page
        registration.installing!.addEventListener('statechange', () => {
          if (registration.waiting) {

            // Perform the reload
            window.location.reload();
          }
        });
      });
    }).catch(error => {
      console.log('Service worker registration failed:', error);
    });
  });
}

This listener will wait for the service worker to register and then listen for any updates. When a new service worker is found, it will wait until it becomes active and then reload the page.

  1. Finally, when you are ready to deploy your app, make sure to remove the skipWaiting and clientsClaim options from your serviceWorker.js file:
// serviceWorker.js
register(null);

This will ensure that the service worker is activated as soon as it is updated, without any additional prompting.