title: React Service Worker: Uncaught SyntaxError: Unexpected token '<'
body: <p>I'm customizing my service worker in a React app created with CRA.</p>
  <p>The only change I made was to create a function to poll for live updates. So, my file looks like this:</p>
  <pre><code>// 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://cra.link/PWA
  
  const isLocalhost = Boolean(
    window.location.hostname === 'localhost' ||
      // [::1] is the IPv6 localhost address.
      window.location.hostname === '[::1]' ||
      // 127.0.0.0/8 are considered localhost for IPv4.
      window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
  );
  
  const POLLING_LOOP_MS = 30000;
  
  type Config = {
    onSuccess?: (registration: ServiceWorkerRegistration) =&gt; void;
    onUpdate?: (registration: ServiceWorkerRegistration) =&gt; void;
  };
  
  export function register(config?: Config) {
    if (process.env.NODE_ENV === 'production' &amp;&amp; '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', () =&gt; {
        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(() =&gt; {
            console.log(
              'This web app is being served cache-first by a service ' +
                'worker. To learn more, visit https://cra.link/PWA'
            );
          });
        } else {
          // Is not localhost. Just register service worker
          registerValidSW(swUrl, config)
        }
      });
    }
  }
  
  function registerValidSW(swUrl: string, config?: Config) {
    navigator.serviceWorker
      .register(swUrl)
      .then((registration) =&gt; {
        registration.onupdatefound = () =&gt; {
          const installingWorker = registration.installing;
          if (installingWorker == null) {
            return;
          }
  
          installingWorker.onstatechange = () =&gt; {
            if (installingWorker.state === 'installed') {
              if (navigator.serviceWorker.controller) {
                if (config &amp;&amp; config.onUpdate) {
                  config.onUpdate(registration);
                }
              } else {
                // At this point, everything has been precached.
                // It's the perfect time to display a
                // &quot;Content is cached for offline use.&quot; message.
                console.log('Content is cached for offline use.');
  
                // Execute callback
                if (config &amp;&amp; config.onSuccess) {
                  config.onSuccess(registration);
                }
              }
            }
          };
        };
  
        pollLiveSWUpdates(registration);
      })
      .catch((error) =&gt; {
        console.error('Error during service worker registration:', error);
      });
  }
  
  function checkValidServiceWorker(swUrl: string, config?: Config) {
    // Check if the service worker can be found. If it can't reload the page.
    fetch(swUrl, {
      headers: { 'Service-Worker': 'script' },
    })
      .then((response) =&gt; {
        // 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 &amp;&amp; contentType.indexOf('javascript') === -1)
        ) {
          // No service worker found. Probably a different app. Reload the page.
          navigator.serviceWorker.ready.then((registration) =&gt; {
            registration.unregister().then(() =&gt; {
              window.location.reload();
            });
          });
        } else {
          // Service worker found. Proceed as normal.
          registerValidSW(swUrl, config);
        }
      })
      .catch(() =&gt; {
        console.log('No internet connection found. App is running in offline mode.');
      });
  }
  
  function pollLiveSWUpdates(registration: ServiceWorkerRegistration) {
    setInterval(async () =&gt; {
      await registration.update();
    }, POLLING_LOOP_MS);
  }
  
  export function unregister() {
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.ready
        .then((registration) =&gt; {
          registration.unregister();
        })
        .catch((error) =&gt; {
          console.error(error.message);
        });
    }
  }
  </code></pre>
  <p>So, when there is a new update, I trigger the <code>onUpdate</code> to show a toast in the application. When I click on the Update button in my toast, I skip the waiting status and refresh the page, so the new service work is registered and running. This is working properly then.</p>
  <p>However, if a new update is found and I just refresh the page without skipping the current waiting by using my toast, I get the following error:</p>
  <pre><code>Uncaught SyntaxError: Unexpected token '&lt;'
  </code></pre>
  <p>It seems that the current service worker is trying to get a cached chunk js file that is not available anymore. And the response for that file is an HTML of my index.html. I had some CSP and cache-control policies for my headers, but I have removed all of them and the error persists.</p>
  <p>And some times the error is different for the same case:</p>
  <pre><code>Refused to execute script from 'http://localhost:5001/static/js/[DASH].chunk.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
  </code></pre>
  <p>The same thing happens if I try to use the built-in serviceWorkerRegistration.ts file.</p>
  <p>What am I missing here?</p>