I have a React app created by using create-react-app. By default, this tool creates a serviceWorker.js file for us and I am using this to register a service-worker. Furthermore, the documents suggest using google's workbox wizard to create a service-worker.js used to manage my website for offline purposes. The goal is for me to store an offline.html page in the browsers cache and whenever there is no online connection, render the cached offline.html page.

I am successful in storing the offline.html in cache and as you can see below, it is stored in the precached URLS (check last two rows). enter image description here

I can also manually navigate to the offline.html if i change the URL in my browser.

However, I am having trouble automatically grabbing this file and rendering it whenever there isn't a connection.

In the serviceWorker.js code that is generated for me from CRA theres a function called checkValidServiceWorker:

function checkValidServiceWorker(swUrl, config) {
  // Check if the service worker can be found. If it can't reload the page.
    .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(() => {
      } else {
        // Service worker found. Proceed as normal.
        registerValidSW(swUrl, config);
    .catch(() => {
        'No internet connection found. App is running in offline mode.'
      const OFFLINE_URL = '/.offline/offline.html';
      return caches.match(OFFLINE_URL).then((response) => {

So in the catch part of the function, I want to do my redirect because thats the logic that runs when we are offline. I read a lot of docs and my current solution doesn't work. Any ideas on how to redirect in my serviceWorker?

0 Answers