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 gett