🎄 Get 50% off from our JavaScript course for the holidays! 🎄
How to Sync Your Client and Server After Being Offline

How to Sync Your Client and Server After Being Offline

Save offline changes to sync later with your server

Ferenc Almasi • 🔄 2021 November 11 • 📖 5 min read

PWAs have become more and more commonplace. People want to access your content in uncertain conditions or even when there’s no internet connection at all. To battle this, we have service workers that can help you eliminate the problems of being offline. But what happens once the connection is back and users have pending changes?

Most of the time, these changes are lost. Since there’s no connection, they are not saved to a database. But can we change this? The answer is yes. This is the time when you want to sync the changes to ensure they are kept and nothing is lost.

So how do we do this? Everything starts when things go offline.

Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
JavaScript Course

Detecting Offline State

For detecting network changes, we have some options. First, you can add event listeners for online and offline changes:

window.addEventListener('offline', () => { ... });
window.addEventListener('online',  () => { ... });
offline.js
Copied to clipboard!

This is especially useful when you want to give some feedback to the user about the changes in network conditions.

Going offline shows banner
Banner is shown when the user goes offline

Apart from event listeners, we can also check the value of navigator.onLine. If this value turns out to be true, we can save changes locally only to sync them later with the server.


Queue Updates

To queue network requests, we need to store information on the user’s machine. We also need to account for page refreshes or even closing the browser altogether. This can be done with the use of localStorage. Let’s create an offlineService that can catch network requests to later reuse them for syncing:

const offlineService = {
    
    getQueue() {
        return JSON.parse(localStorage.getItem('queue') || '[]');
    },

    deferRequest(payload) {
        const queue = this.getQueue();

        queue.push(payload);

        localStorage.setItem('queue', JSON.stringify(queue));
    },

    clearQueue() {
        localStorage.removeItem('queue');
    }
};
offlineService.js
Copied to clipboard!

For this, we can create an object with three different methods:

Note that we have to use JSON.parse and JSON.stringify to be able to save to localStorage.

By exporting the object and importing it to a service that handles API requests, we can use navigator.onLine to check the network condition:

// Service that receives all requests to the API
APIRequest(params) {
    if (!navigator.onLine) {
        offlineService.deferRequest(params);
    } else {
        return fetch(params.url, {
            body: params.body,
            method: params.method,
            headers: params.headers
        }).then(response => {
            return response.json();
        }).catch(error => {
            console.log(error);
        });
    }
}
httpService.js
Copied to clipboard!

And we either use our newly created offlineService to defer requests or we continue sending them as usual. Every time a request is made, this will create a new object in the queue array with the request URL, body, method, and headers—everything that is needed to later sync pending changes with the server.


Syncing With Database

The last thing to do is to finally sync the changes with the server once the connection is restored:

window.addEventListener('online', () => {
    if (offlineService.getQueue().length) {
        const deferredRequests = offlineService.getQueue();
  
        deferredRequests.forEach(async payload => await APIRequest(payload));
        
        offlineService.clearQueue();
    }
});
sync.js
Copied to clipboard!

First, we can check if there’s anything in the array just to be sure. If there is, we get it, and for each request that has been queued, we call the function that handles the API requests with the payload provided. Then we can clear the queue since nothing needs to updated again.


Summary

All that’s left to do is to check if everything works as expected. I also added some CSS animation to it to show the user that something is going on in the background:

Trying out syncing with DB

When I go offline, first the notification comes up. This is due to the event listener added to the offline event. Then I try to add a couple of items and set the connection back to online in the Network tab. And we get back four requests for the four changes.

This combined with a service worker and PWA configuration can really take the offline experience of your application to the next level. Users can confidently keep on working even when the connection is lost. And since all information is stored inside localStorage, this information will survive even if you close the tab.

Thank you for reading through. Are there any ways you try to deal with being offline? If so, let us know in the comments section below.

Share on
  • twitter
  • facebook
JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in less time.

Learn More

Recommended

🎉 Thank you for subscribing to our newsletter. x