Learn how to customize Google Workbox’s default behavior for a service worker in your React app. This articles explains how to modify the behavior of the service worker life cycle, enabling fully automated updates of your app in the background. Includes a bonus section with a React Bootstrap component alert for app update announcements.

Setting Up A Service Worker

The smart way to get started with service workers is to use create-react-app, which provides a simple way to scaffold a basic service worker for a React app:

npx create-react-app hello-world --template cra-template-pwa

This quick start approach gives your site basic offline capabilities by adding two boilerplate js modules to the root of your project, service-worker.js and serviceWorkerRegistration.js. It also installs Google’s npm package workbox-sw that vastly simplifies everything about managing a service worker.

By the way, a couple of reference sources that I came across bear mentioning. First, the web site create-react-app.dev contains documentation that explains how to customize these two boiler plate files to optimize your site’s offline behavior. Additionally, if you’re just getting started with service workers then I’d recommend this blog post from Danielly Costa, “Showing ‘new version available’ notification on create-react-app PWAs“. It’s well-written, easy to follow, it’s relatively current as of this publication, and it’s what I used when I was just getting started.

Moving along, the boiler plate code adds the following to your React app:

  • Registers a service worker for your React app

  • Automatically detects and installs updates to your service worker and offline content

  • Sets up basic caching to enable performant offline viewing of your site’s static content

The only thing that I dislike is that this boiler plate does several things to bring attention to your site’s offline capabilities. I don’t want that. I want my site to be resilient with regard to Internet connectivity but I’d rather that my users don’t even notice when they’re offline. The less they notice, the better. Summarizing what you get versus what I actually wanted:

The default service worker life cycle

By default Workbox registers a service worker and then checks for and downloads any updates to your code base. At that point, it pauses the update process until all browser tabs and windows containing your app have been closed. Then, only upon the user’s next visit to your site does it actually update the locally cached content to activate these changes in the user’s browser. Additionally, just a slightly annoying side effect is that the boiler plate code sends messages to the javascript console any time the app is being accessed offline, and also when code is updated.