How to do offline data sync in PWA

Progressive web applications (PWAs) are web applications that contain the best features of both web and mobile applications. As a result, a PWA provides a hybrid user interface which helps provide a seamless experience. The idea of a PWA was introduced by Steve Jobs in 2007 at the inception of the first iPhone, but the first PWA was created in 2015. Nowadays, converting a website into a PWA is as simple as a few clicks. The Google Lighthouse extension on Google Chrome generates a score for converting a website into a PWA, which demonstrates the feasibility of converting a simple web app into a PWA.

Methods of implementing offline data sync in PWA

Among the many useful features of PWA, one of the most popular ones is offline data sync. This feature allows users to back up their site to their devices so the website remains accessible in case of disconnection. There are multiple methods to perform offline data sync. In this Answer, we will briefly discuss each.

Service workers

One common and easy offline data sync method is implementing service workers. In this methoid, static and dynamic web assets are cached in service workers through web files in the web application. Let’s look at the implementation of a service worker for a React application below.

Registering a service worker

The following code will check if a service worker is registered. If it is not registered, the service worker will be initialized through the service-worker.js file.

if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js')
.then(registration => {
console.log('Service Worker registered with scope:', registration.scope);
})
.catch(error => {
console.error('Service Worker registration failed:', error);
});
}

Caching data for service worker

Let's look at the code that initializes files to be cached.

self.addEventListener('install', event => {
event.waitUntil(
caches.open('my-cache-name').then(cache => {
return cache.addAll([
'/index.html',
'/styles.css',
'/script.js',
// ...other assets to cache
]);
})
);
});
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(response => {
return response || fetch(event.request);
})
);
});

The code is mainly divided into the following two main parts:

  • The first part of the code with the install tag initializes the content to be cached.

  • The second part of the code with the fetch tag fetches the content to be cached through the network calls.

Reloading the cached files

If the user goes offline, the code snippet below will make a network call to check if the user is online. However, if the user is online, it will cache the files again to keep up-to-date with any changes in the file. In case there is no response, it will upload the cached content with the name, my-cache-name.

self.addEventListener('fetch', event => {
event.respondWith(
caches.open('my-cache-name').then(cache => {
return cache.match(event.request).then(response => {
const fetchPromise = fetch(event.request).then(networkResponse => {
cache.put(event.request, networkResponse.clone());
return networkResponse;
});
return response || fetchPromise;
});
})
);
});

Local data storage 

Another offline data sync method is backing up the data locally on the user's device. If the user loses internet connectivity, the system can automatically reload the user to the saved state of the webpage.

Creating offline UI

Offline data synchronization in PWAs can also be implemented by adding UI elements that inform the user when they go offline. In that case, a pop-up message tells the user that their data will be synchronized once they return online. An example of this is the Google Docs offline edit mode. By turning on this mode, the user can edit their documents offline. The user’s data gets backed up to the server once they are online.

Background synchronization

Adding background APIs to web applications helps in background synchronization. The API synchronizes the user's data to the server after a specific time. This API runs in the background while updating the users' data on the servers.

API connection
API connection

The implementation for this can be done with the following code:

if ('SyncManager' in self) {
navigator.serviceWorker.ready.then(registration => {
return registration.sync.register('data-sync');
});
}

This code checks if the Sync Manager API is available in the browser. If it's available, it registers a sync event with the tag data-sync. This event keeps making requests even when the user is offline. As the user gets back online, the SyncManager API uploads the updated assets back to the server.

Things to keep in mind during PWA implementation

During an offline data sync, there are a few things that the developer needs to keep in mind. Some of them are mentioned below.

Data synchronization

The developer should decide which of the following data synchronization methods they need to implement:

  • Make the application usable offline and update the data to the server once the user returns online.

  • Cache a copy of the webpage after a small interval so the user does not lose his progress.

  • Create methods that resolve issues during data synchronization for smooth UX.

Handling conflicts and errors  

The developer should create a system that manages data synchronization conflicts and network errors during synchronization. If the server receives multiple copies of the same document once the user returns online, the system should be able to handle which copy should be updated in the server.

Conclusion

Offline data synchronization is a challenging feature to implement, as careful planning and advanced-level networking knowledge are needed for smooth and error-free implementation of server-to-client synchronization. Once a developer is aware of the various aspects mentioned in this Answer, they can create a seamless user experience.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved