Background Sync with Workbox
What you'll learn: How to automatically retry failed network requests using Workbox's BackgroundSync plugin when the user regains connectivity.
You've already learned about the Background Sync API and how to manually queue failed requests. Workbox makes this pattern dramatically simpler through its BackgroundSync plugin. Instead of manually storing failed requests in IndexedDB and writing sync handlers, Workbox handles the entire flow for you.
How It Works
The BackgroundSyncPlugin automatically intercepts any failed network requests from routes you specify. When a request fails (network unavailable, server error, etc.), Workbox stores it in IndexedDB. Once connectivity returns, it automatically retries those requests during the browser's sync event.
Think of it like a smart mail carrier: if they can't deliver a package today, they automatically hold it and try again tomorrow—no extra paperwork needed.
Basic Usage Pattern
You add the plugin to a route strategy. Here's the simplest example:
import { registerRoute } from 'workbox-routing';
import { NetworkOnly } from 'workbox-strategies';
import { BackgroundSyncPlugin } from 'workbox-background-sync';
const bgSyncPlugin = new BackgroundSyncPlugin('myQueueName', {
maxRetentionTime: 24 * 60 // Retry for up to 24 hours
});
registerRoute(
({url}) => url.pathname.startsWith('/api/'),
new NetworkOnly({
plugins: [bgSyncPlugin]
})
);
Now any failed API requests automatically queue and replay when online. The plugin handles registration, storage, retry logic, and cleanup.
Configuration Options
The plugin accepts maxRetentionTime to limit how long requests stay queued, and onSync callbacks to customize replay behavior—but the defaults work great for most scenarios.
Key Takeaway: Workbox's BackgroundSyncPlugin eliminates boilerplate code by automatically queueing failed requests and replaying them when connectivity returns, turning complex offline resilience into a simple plugin configuration.