Concept Explanation
Caching makes your app fast. These two APIs make it reliable — they let it do work when nobody is looking at it.
Background Sync is the outbox in an email client. The user hits Send on a train with no signal. Instead of an error toast, the request goes into a queue and the browser promises to retry it the moment connectivity returns, even if the tab has been closed since.
Push is the doorbell. Your server can wake the service worker on a device with no tab open at all, and the worker shows a notification. Note the direction: this is your server reaching the user, not your page polling for changes.
Both run in the service worker, because the service worker is the only part of your app that outlives the page.
Syntax or Core Structure
Queueing a request for later
// In the page
const reg = await navigator.serviceWorker.ready;
await saveToIndexedDB(draft); // persist the payload first
await reg.sync.register('send-drafts');
// In sw.js
self.addEventListener('sync', (event) => {
if (event.tag === 'send-drafts') {
event.waitUntil(flushDrafts()); // browser retries if this rejects
}
});
Subscribing to push
const reg = await navigator.serviceWorker.ready;
const sub = await reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: VAPID_PUBLIC_KEY
});
await fetch('/api/subscriptions', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(sub)
});
Receiving a push and handling the click
self.addEventListener('push', (event) => {
const data = event.data.json();
event.waitUntil(
self.registration.showNotification(data.title, {
body: data.body,
icon: '/icon-192.png',
data: { url: data.url },
tag: 'order-updates' // replaces the previous one instead of stacking
})
);
});
self.addEventListener('notificationclick', (event) => {
event.notification.close();
event.waitUntil(self.clients.openWindow(event.notification.data.url));
});
Key Features
- Tags identify the job. Registering the same sync tag twice coalesces into one retry, which is what you want for "flush the outbox".
- The browser owns the retry schedule. It backs off exponentially and gives up after a few attempts. You do not control the timing.
- VAPID keys identify your server to the push service so only you can send to your subscribers.
userVisibleOnly: trueis mandatory in Chrome: every push must result in a visible notification. Silent background pushes are not allowed.- Periodic Background Sync exists for scheduled refreshes but is limited to installed apps with high engagement, so treat it as a bonus.
Real World Example
A field-inspection app used in warehouses with dead spots. Inspectors fill in forms where there is no signal. Each submission is written to IndexedDB and a sync tag is registered. When the technician walks back into Wi-Fi range, the service worker drains the queue, and a push notification confirms the batch was accepted by the server. From the inspector's point of view the app simply never failed, which is the entire product requirement.
Common Mistakes
- Prompting for notification permission on page load. Users deny it reflexively, and a denial is close to permanent. Ask after they opt into something specific.
- Keeping the queued payload only in memory. The worker is terminated between the failed request and the retry. Persist to IndexedDB first, always.
- Assuming iOS parity. Safari requires the app to be installed to the home screen before push works at all, and background sync support lags. Feature-detect and degrade.
- Not handling
notificationclick. The user taps your notification and nothing happens, which is worse than not sending it. - Sending a push with no visible notification. Chrome will warn the user that your site is doing background work, and may revoke permission.
- Forgetting to prune dead subscriptions. A
410 Gonefrom the push service means delete that record.
Best Practices
- Feature-detect both APIs (
'sync' in registration,'PushManager' in window) and always ship a plain-fetch fallback. - Make the queued work idempotent; a retried request may arrive twice.
- Use a
tagon notifications so a chatty server does not bury the user in a stack of them. - Explain the value before you ask for permission, and give the user a way to turn it off inside your UI.
- Test with DevTools: the Application panel can trigger a sync event and send a fake push payload.
Practice Exercises
- The Outbox: Build a form that writes to IndexedDB, registers a sync tag, and flushes on reconnect. Verify it by going offline, submitting, then coming back online.
- The Fake Push: Use the Application panel's "Push" button to deliver a payload to your service worker and render a notification from it.
- The Permission Flow: Write the smallest possible UI that explains why you want notifications, requests permission only on click, and handles the
deniedcase gracefully.