Easy Workbox Integration with create-react-app
Tags: javascript, react, workbox, code
Published: 2021-01-01 22:43:41

---
title: Easy Workbox Integration with create-react-app
tags: javascript, react, workbox, code
published: true
canonical_url: https://kelvinmwinuka.com/easy-workbox-integration-with-create-react-app/?utm_source=rss&utm_medium=rss&utm_campaign=easy-workbox-integration-with-create-react-app
---

Recently, I was in a situation that required workbox integration for background sync in an application.  After some trial, error and success, I decided to write this article to demonstrate the easiest way I've found to integrate workbox with create-react-app.

<!-- wp:paragraph -->
<p>This article assumes basic knowledge of create-react-app, workbox and the react framework, as we will be using some terminology associated with these technologies. There's no need to be a pro, beginner-level knowledge should suffice.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>1. Update serviceWorker.js</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The first step is updating the serviceWorker.js file within the src folder. We will be updating the register function. At the moment, it looks like this:</p>
<!-- /wp:paragraph -->

```javascript
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);
      }
    });
  }
}
```

We're going to update the following line:

```javascript
 const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
```

To:

```javascript
const swUrl = `${process.env.PUBLIC_URL}/custom-service-worker.js`;
```

<!-- wp:paragraph -->
<p>This will allow us to create and register our own custom service worker file named 'custom-service-worker.js'. You can name this whatever you like.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If you'd like to be able to test this in development, disable the production environment check in the following line:</p>
<!-- /wp:paragraph -->

```javascript
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) 
```

<!-- wp:heading {"level":3} -->
<h3>2. Create custom service worker file</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The next step is creating the custom service worker file in the public folder of our application. This should match the name we used in step 1. In our case, 'custom-service-worker.js'</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We can import and use workbox from here:</p>
<!-- /wp:paragraph -->

```javascript
importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.1.2/workbox-sw.js')

if (workbox) {
  console.log(`Yay! Workbox is loaded 🎉`);
} else {
  console.log(`Boo! Workbox didn't load 😬`);
}
```

<!-- wp:paragraph -->
<p>Once Workbox is loaded from the CDN, a workbox object is created allowing us to make use of the workbox API.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We can self-host workbox by downloading the files into a folder in our public folder in one of 2 ways:</p>
<!-- /wp:paragraph -->

<!-- wp:list {"ordered":true} -->
<ol><li><a aria-label="undefined (opens in a new tab)" href="https://developers.google.com/web/tools/workbox/modules/workbox-cli#copylibraries" target="_blank" rel="noreferrer noopener">Using workbox cli's copyLibraries command</a></li><li><a href="https://github.com/GoogleChrome/workbox/releases" target="_blank" aria-label="undefined (opens in a new tab)" rel="noreferrer noopener">Downloading the files from a Github release</a></li></ol>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Note that workbox will cache all modules referenced when loaded through the CDN. These modules will then be available for offline use after the first time they are referenced.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Therefore, you do not need to host workbox yourself if this is your concern.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In order to load workbox if we're self hosting, we will need to do the following:</p>
<!-- /wp:paragraph -->

```javascript
importScripts('/third_party/workbox/workbox-sw.js');

workbox.setConfig({
  modulePathPrefix: '/third_party/workbox/'
});
```

<!-- wp:paragraph -->
<p>In this instance, the workbox folder is contained within the third_party folder inside our application's public folder.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now we can finally use workbox. We can use destructuring in order to access the different workbox modules:</p>
<!-- /wp:paragraph -->

```javascript
const { backgroundSync, routing, strategies } = workbox
```

<!-- wp:heading {"level":3} -->
<h3>3. Register service worker</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The final step is registering the service worker in our application. Navigate to the index.js file in the src folder and change the following line:</p>
<!-- /wp:paragraph -->

```javascript
serviceWorker.unregister();
```

To:

```javascript
serviceWorker.register();
```

The post [Easy Workbox Integration with create-react-app](https://kelvinmwinuka.com/easy-workbox-integration-with-create-react-app/) appeared first on [Kelvin Mwinuka](https://kelvinmwinuka.com).

If you enjoyed this article, consider following my [website](https://kelvinmwinuka.com) for early access to my content before it gets published here (don’t worry, it’s still free with no annoying pop-up ads!). Also, feel free to comment on this post. I’d love to hear your thoughts!