Published on 29.8.2019
In recent years, Progressive Web Apps (PWAs) have become a hot topic in the world of web development. PWAs combine the best of both web and mobile apps, offering features like offline access, fast loading times, and native-like interactions, all while being hosted on the web.
If you’re building a React app, you might be wondering how to turn it into a PWA. In this post, we’ll walk through how to enable PWA features in your React app, including adding service workers, caching, and ensuring your app works offline.
By the end of this tutorial, you’ll have a React app that behaves like a native app, with features that can work even when the user has a poor or no internet connection.
What is a Progressive Web App?
A Progressive Web App (PWA) is a web app that uses modern web capabilities to deliver an app-like experience. PWAs are designed to work seamlessly across devices, providing the following benefits:
- Offline functionality: The app can work even without a network connection.
- Installability: Users can install the app on their home screen like a native mobile app.
- Performance: PWAs load quickly, even on slow networks.
- Push notifications: PWAs can send notifications to users, even when they’re not actively using the app.
The key to making your app a PWA is integrating service workers and caching mechanisms.
How to Turn Your React App into a PWA
To make your React app a Progressive Web App, you need to follow these steps:
- Use Create React App (CRA): The easiest way to set up a React app with PWA features is by using the Create React App tool, which provides built-in support for service workers and caching.
- Enable Service Worker: Service workers enable offline capabilities by caching assets and data. We’ll enable the service worker to handle caching for us.
Step 1: Creating a React App with PWA Support
If you haven’t created your React app yet, the best approach is to use Create React App (CRA), which includes PWA support out of the box.
You can create a new React app with PWA support using the following command:
npx create-react-app my-pwa-app
After running this, navigate to the new project folder:
cd my-pwa-app
Now, if you open the project, you’ll find that it already includes service worker support. CRA sets up everything for you to get started with PWA features.
Step 2: Enabling the Service Worker
In a Create React App project, the service worker is disabled by default in the development build but can be enabled for production builds. This ensures that the app will behave like a PWA when deployed.
Let’s enable the service worker.
src/index.js
In the src/index.js file, look for the following code:
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorkerRegistration from './serviceWorkerRegistration';
import { BrowserRouter as Router } from 'react-router-dom';
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('root')
);
// Change serviceWorker.unregister() to serviceWorker.register()
serviceWorkerRegistration.register();
Here, we import serviceWorkerRegistration and call register() instead of unregister(). This will ensure that the service worker is registered in the production build and will manage the caching of assets and data.
Why Use Service Workers?
A service worker is a script that runs in the background, independent of the web page. It helps manage caching, push notifications, and other background tasks. For a PWA, service workers allow the app to be installed and function offline by caching important assets (like HTML, CSS, JS, images).
Step 3: Caching with the Service Worker
Once the service worker is enabled, it can start caching assets automatically. However, you can customize how assets are cached by modifying the service worker file.
- Edit the Service Worker: In CRA, the service worker is located in
src/service-worker.js. This file handles caching and managing network requests. - Caching Strategies: By default, CRA’s service worker uses a caching strategy called “cache-first”, which tries to load resources from the cache before falling back to the network. You can modify the service worker if you need more control over caching strategies, such as network-first or stale-while-revalidate.
Step 4: Handling the Manifest File
Another important part of turning your React app into a PWA is adding a manifest file. The manifest is a simple JSON file that provides metadata about your app, such as the name, icon, and theme color. This file allows users to install your app on their home screens.
public/manifest.json
In your public/manifest.json file, make sure the following fields are properly configured:
{
"short_name": "React PWA",
"name": "My React Progressive Web App",
"icons": [
{
"src": "favicon.ico",
"sizes": "16x16 32x32 48x48",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "logo512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"start_url": ".",
"background_color": "#ffffff",
"display": "standalone",
"theme_color": "#000000"
}
- icons: The app will use these icons when installed on a user’s device. You can provide multiple sizes to ensure your app looks good on different devices.
- start_url: The URL to open when the app is launched from the home screen.
- background_color: The background color of the splash screen when the app is launched.
- theme_color: The theme color that affects how the app looks in the browser (e.g., the address bar color).
Step 5: Testing and Deploying Your PWA
Once you’ve configured the service worker and manifest, you’ll want to test the PWA behavior.
- Test Offline Capabilities: In Chrome DevTools, you can simulate offline behavior by going to the Network tab and enabling Offline mode. When you reload the page, your app should load from the cache, and you should be able to interact with it even without an internet connection.
- Build the App for Production: To build your app for production and test the PWA features, run the following command:
npm run build
This will create an optimized production build in the build/ folder, which you can then deploy to a hosting provider (like Netlify, Vercel, or Firebase Hosting).
Conclusion
Congratulations! You’ve now turned your React app into a Progressive Web App (PWA). By following these steps, you’ve:
- Enabled service workers for offline functionality.
- Configured a manifest file for installation on user devices.
- Optimized your app for performance using caching strategies.
PWAs are a fantastic way to make your web apps feel more like native apps, with features such as offline access, push notifications, and smooth user experiences. React, together with service workers and PWAs, opens up a world of possibilities for building fast, reliable, and engaging applications.
As web capabilities continue to evolve, PWAs are becoming a must-have for developers looking to build modern, resilient applications.
Happy coding, and enjoy building your PWA with React!