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!
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.
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.
Service workers provide essential support for running a progressive web application. A service worker takes the form of a JavaScript file that runs in a separate, non-blocking thread from the main browser thread.
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.
Before getting started, you’ll need the following:
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.
service-worker.js
fileTo 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.
Or, if you prefer to write your app in TypeScript over JavaScript, here’s how you would create a project that includes a starter src/service-worker.js
file:
npx create-react-app my-app --template cra-template-pwa-typescript
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:
serviceWorkerRegistration.register();
The src/service-worker.js
file is now registered and ready to play its key role in providing an offline-first experience for your users.
The starter src/service-worker.js
file that you added using the cra-template-pwa
or 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 src/service-worker.js
.
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:
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.
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.
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowThe useReducer React Hook is a good alternative to tools like Redux, Recoil, or MobX.
Node.js v22.5.0 introduced a native SQLite module, which is is similar to what other JavaScript runtimes like Deno and Bun already have.
Understanding and supporting pinch, text, and browser zoom significantly enhances the user experience. Let’s explore a few ways to do so.
Playwright is a popular framework for automating and testing web applications across multiple browsers in JavaScript, Python, Java, and C#. […]
5 Replies to "PWA with Create React App and service workers"
Hello… what if I already created the app without the templato. How can I add the same service-worker.js file to my project?
I had the same question.
I think you just need to add your file to the public folder and register it as you normally would then. The workbox stuff gets trickier though if you’re using that. There is a good walkthrough on making service workers with CRA on Udemy if you search there for `custom service worker CRA without ejecting`.
Can a pwa not display latest updated build without closing and opening again?
Goto your public folder and create One file called serviceWorker.js and include that file inside index.html by registering. Check more on internet