Course contentsShow
← Web Development
Lesson 2336 of 2,98242. Progressive Web AppsFree lesson

Handling the sync Event in Service Workers

Writing service worker sync event handlers to process queued tasks when connectivity is restored.

Handling the sync Event in Service Workers

What you'll learn: How to write sync event handlers that process queued tasks when your user's connection returns.

Now that you can register a sync event, you need to handle it in your service worker. This is where the magic happens—when the browser detects connectivity has been restored, it fires the sync event, giving you a chance to process all those queued tasks you stored while offline.

Writing the sync Event Handler

In your service worker file, you listen for the sync event just like you do for install, activate, or fetch. The event gives you access to a tag property that matches what you registered, letting you route different types of sync operations appropriately.

self.addEventListener('sync', event => {
  if (event.tag === 'send-messages') {
    event.waitUntil(sendQueuedMessages());
  }
});

The event.waitUntil() method is crucial—it tells the browser to keep the service worker alive until your promise resolves, ensuring your task completes even if the user has closed all tabs.

Processing Your Queue

Inside your handler function, retrieve items from storage (like IndexedDB), attempt to send them, and clean up successful sends:

async function sendQueuedMessages() {
  const db = await openDatabase();
  const messages = await getQueuedMessages(db);
  
  for (const message of messages) {
    await fetch('/api/messages', {
      method: 'POST',
      body: JSON.stringify(message)
    });
    await deleteMessage(db, message.id);
  }
}

If any request fails, the sync will fail and the browser will automatically retry later with exponential backoff.

Key Takeaway: The sync event handler in your service worker processes queued tasks when connectivity returns, using event.waitUntil() to ensure completion and automatic retry on failure.