Editor’s note: This article was last updated 14 July 2022 to reflect Create React App v5.x.
In this tutorial, we’ll cover what you need to know about using service workers to build a progressive web app with Create React App. We’ll explain what PWAs are, discuss what a service worker is, then demonstrate the steps you’ll need to follow to set up service workers in a React application. Let’s get started!
- What is a progressive web application?
- What is a service worker?
- How to set up service workers for Create React App
What is a progressive web application?
A progressive web app is an enhanced type of web app that has some of the same capabilities as a native or platform-specific app.
For example, progressive web apps can be installed directly on a user’s home screen and can run in a standalone window. These apps run fast and reliably under poor network conditions and can even function offline.
Think of how your typical mobile user moves through changing environments while using your app. For example, they might start out in a building that has a reliable high-speed network. But, when they walk out to the street, they may lose wifi and fall back to cellular connectivity.
They might catch a strong 4G or even 5G signal, or, they may hit a low-service dip that only has 3G. How can they stay on your app in all network conditions, even when they have no connectivity at all?
A progressive web app lets you reach your users wherever they are and serve them fast and reliable user experiences in any network environment.
What is a service worker?
A service worker is a special type of web worker that intercepts network requests from a web app and controls how these requests are handled. In particular, the service worker can manage the caching of resources and retrieval of these resources from the cache, thereby supporting the offline-first mode that’s crucial for PWAs.
Create React App v4.0 and later versions come equipped with built-in support for the
InjectManifest plugin from Workbox, which handles the compiling and injection of service workers into your app’s pre-caching list.
How to set up service workers for Create React App
Before getting started, you’ll need the following:
- Create React App ≥v4.0
- A production web server that supports HTTPS
Keep in mind that for security reasons, service workers and progressive web app features will only run over HTTPS. Users can still run your app over HTTP, but they won’t have access to offline-first mode and all the other great features of service workers.
Create a project and add a
To leverage Create React App’s integration with Workbox’s
InjectManifest plug-in, you’ll simply create a new project using a custom PWA template:
npx create-react-app my-app --template cra-template-pwa
The template automatically adds a
src/service-worker.js file to your project. This file contains a basic service worker that you can come back to later and customize to your liking.
npx create-react-app my-app --template cra-template-pwa-typescript
Register the service worker
By default, service workers don’t become active and available for use until you register them. To learn more, you can read up on the fundamentals of the service worker life cycle.
Go to the
src/index.js file in your project and find the following lines of code:
// If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://cra.link/PWA serviceWorker.unregister();
To register the service worker for use, simply modify the last line so that it looks like the following:
src/service-worker.js file is now registered and ready to play its key role in providing an offline-first experience for your users.
Customize the service worker
src/service-worker.js file that you added using the
cra-template-pwa-typescript template comes with the basic logic for underpinning your progressive web app. If you want to expand the offline-first capabilities of your app, you can easily customize
To support pre-caching, make sure that you assign the
self.__WB_MANIFEST value to a variable that can be recognized by the
InjectManifest plug-in. The plugin needs to see this value in order to generate its manifest of URLs for pre-caching.
Some examples of how you can customize the
src/service-worker.js file include:
- Using additional service worker packages from Workbox
- Adding push notifications
- Fine-tuning background data synchronization
- Centralizing updates to shared geolocation or gyroscope data
- Adding the ability to handle traffic originating from a different domain
As the Service Worker API continues to evolve, you can look forward to being able to support even more features and use cases with your PWAs.
Help users navigate through your progressive web app
Now that you’ve configured your project to support service workers, it’s time to make sure your users are ready and able to take full advantage of offline-first mode. Since progressive web apps behave a little differently from standard web apps, it’s a good idea to educate your users so that they can make the most of their experience.
You can help your users by showing in-app messages that remind them to follow certain protocol. For example, you can remind them to use a browser that supports service workers, like Chrome, Firefox, Opera, Samsung Internet, Safari, or Edge. Keep in mind that service workers aren’t supported by any browser in private or incognito mode.
Once the service worker has initially populated the caches, you can show your users a message informing them that the app can be used offline.
By default, a service worker is kept on standby after it fetches content updates. As a result, users won’t be able to see the changes until after they close all open tabs and load a fresh page, so you can remind your users to close their existing browser tabs.
Turning your standard web app into a PWA is no sweat thanks to Create React App. Once you set up service workers to support an offline-first user experience, your app will be able to reach more users on-the-go, wherever they happen to be.
Get set up with LogRocket's modern React error tracking in minutes:
- Visit https://logrocket.com/signup/ to get an app ID.
- Install LogRocket via NPM or script tag.
LogRocket.init()must be called client-side, not server-side.
- (Optional) Install plugins for deeper integrations with your stack:
- Redux middleware
- ngrx middleware
- Vuex plugin
$ npm i --save logrocket
import LogRocket from 'logrocket';
Add to your HTML:
<script>window.LogRocket && window.LogRocket.init('app/id');</script>