Today, you’ll add a service worker to your React app to enable offline support. Service workers cache resources so your app can function without a network connection, allowing users to interact with your app even when offline.
What You Will Do Today:
- Understand the role of service workers in PWAs.
- Register the default service worker.
- Customize caching strategies to cache specific assets and routes.
Step 1: Understanding Service Workers
A service worker is a JavaScript file that runs in the background, separate from the main application. It acts as a network proxy, allowing it to cache assets and intercept network requests to serve cached data when the network is unavailable.
- Caching: Service workers store static resources, so the app works offline or on low connectivity.
- Lifecycle: Service workers have a lifecycle independent of the app, making them ideal for caching.
Step 2: Registering the Default Service Worker
create-react-app includes a basic service worker setup in public/service-worker.js
and src/serviceWorkerRegistration.js
. To register it:
- In
src/index.js
, importserviceWorkerRegistration
and call theregister()
function:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './styles.css';
import * as serviceWorkerRegistration from './serviceWorkerRegistration';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// Register the service worker
serviceWorkerRegistration.register();
- By registering the service worker, you enable basic offline support. When users load the app, files are cached, allowing them to access previously loaded content even if they lose connectivity.
Step 3: Customizing the Service Worker for Caching Strategies
Let’s customize the service worker to cache additional assets and create caching strategies that determine how resources are stored and retrieved.
- Open
public/service-worker.js
. You’ll add logic here to manage caching. - To cache assets on the first load, update
service-worker.js
as follows:
const CACHE_NAME = 'my-pwa-cache-v1';
const urlsToCache = [
'/',
'/index.html',
'/static/js/bundle.js',
'/static/css/main.css'
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request);
})
);
});
self.addEventListener('activate', (event) => {
const cacheWhitelist = [CACHE_NAME];
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (!cacheWhitelist.includes(cacheName)) {
return caches.delete(cacheName);
}
})
);
})
);
});
Explanation of Code:
- CACHE_NAME: The name of the cache storage for easy versioning.
- urlsToCache: A list of URLs and assets to cache during the
install
phase. - install event: Caches the
urlsToCache
list during the service worker installation. - fetch event: Checks the cache for each request. If available, it serves the cached resource; otherwise, it fetches from the network.
- activate event: Cleans up old caches when a new service worker version is activated.
Step 4: Testing Offline Functionality
- Open your app in Google Chrome and open Developer Tools (
F12
or right-click and select “Inspect”). - Go to the Application tab and select Service Workers on the left sidebar.
- Check Offline under the Network section to simulate offline mode.
- Refresh the page. You should see the app load from the cache, demonstrating that it works offline.
Summary
Today, you added a service worker to your React app to enable offline support by caching key assets. You configured caching strategies to serve cached data when the app is offline.
Tomorrow, you’ll create a manifest file and configure app icons to make your PWA installable.