Lesson 14 / 29

Background sync

Implement background sync to reliably deliver user data even if the connection is lost.

Reliable data delivery

Background sync queues user actions (form submissions, file uploads) and retries them when the connection is restored. The browser handles retries, not your app.

Register background sync

Queue a task for background sync and handle it in the service worker.

// In page
navigator.serviceWorker.ready.then(reg => {
  reg.sync.register('submit-form').then(() => {
    console.log('Sync registered');
  });
});

// In service worker
self.addEventListener('sync', event => {
  if (event.tag === 'submit-form') {
    event.waitUntil(
      fetch('/api/submit', { method: 'POST', body: formData })
        .catch(() => Promise.reject())
    );
  }
});

Output:

Form submission retried automatically when connection is restored.

A common trap

Background sync only works in the service worker and requires proper error handling. Failed syncs are retried with exponential backoff.

Handling sync failures and retries

Implement resilient sync with proper retry logic and user feedback.