Background Sync for Failed Requests
What you'll learn: How to queue failed network requests during offline periods and automatically retry them when connectivity returns using Background Sync.
When users go offline mid-action—submitting a form, posting a comment, or saving data—those requests shouldn't just vanish. Background Sync lets you queue these failed requests and retry them automatically when the network becomes available, creating a seamless user experience.
How It Works
Think of Background Sync as a reliable postal service. When you drop a letter in the mailbox (queue a failed request), the mail carrier (browser) will keep trying to deliver it until it succeeds, even if you're no longer watching.
Here's the pattern:
- Detect the failure: When a
fetch()in your Service Worker fails (network error, timeout, or user offline), catch that error - Store the request: Save the failed request details (URL, method, headers, body) in IndexedDB
- Register a sync event: Call
registration.sync.register('queue-sync')to tell the browser you have pending work - Handle sync in Service Worker: When connectivity returns, your Service Worker receives the
syncevent, retrieves stored requests from IndexedDB, and retries them - Clean up on success: Remove successfully sent requests from the queue
This pattern transforms intermittent connectivity from a showstopper into a minor delay. Users can keep working, and their actions will automatically complete in the background—even if they've closed your app.
Real-World Example
Imagine a user submitting expense reports on a train. They lose signal mid-journey. With Background Sync, those submissions queue up and automatically send when the train reaches the station—no manual retry needed.
Key Takeaway: Background Sync for failed requests turns unreliable networks into a transparent queue system, retrying operations automatically when connectivity returns without user intervention.