I'm building a PWA with a network-first caching strategy. I need custom BackgroundSync logic that queues POST requests like "Like" actions to IndexedDB when offline and replays them when back online, handling any 409 conflict errors that might come up.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Providing custom Background Sync with IndexedDB queue and 409 handling
Here's a service worker setup implementing a network-first GET cache and custom Background Sync that queues POST requests (like "likes") in IndexedDB when offline, replays them on sync, and handles 409 conflict errors by discarding those entries. It includes an IndexedDB helper, fetch handler, sync event, and registration guidance for the main thread.
You can do this entirely in your own service worker without pulling in Workbox. The basic pieces you need are:
A small IndexedDB “outbox” to persist the POST payloads while you’re offline.
A fetch handler that, for your “Like” POSTs, tries the network first and, on failure, enqueues to the outbox and registers a background sync.
A sync handler that drains the outbox and replays the requests when connectivity returns, with explicit handling of 409 Conflict responses.
Here’s a self‑contained example:
js
// sw.js
const DB_NAME = 'pwa-queue';
const DB_STORE = 'outbox';
const SYNC_TAG = 'replay-likes';
// Simple IndexedDB helper
function openOutbox() {
return new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, 1);
req.onupgradeneeded = () => {
req.result.createObjectStore(DB_STORE, { keyPath: 'id', autoIncrement: true });
};
req.onerror = () => reject(req.error);
req.onsuccess = () => resolve(req.result);
});
}
async function addToOutbox(entry) {
const db = await openOutbox();
return new Promise((resolve, reject) => {
const tx = db.transaction(DB_STORE, 'readwrite');
tx.objectStore(DB_STORE).add(entry);
tx.oncomplete = resolve;
tx.onerror = () => reject(tx.error);
});
}
async function getAllFromOutbox() {
const db = await openOutbox();
return new Promise((resolve, reject) => {
const tx = db.transaction(DB_STORE, 'readonly');
const store = tx.objectStore(DB_STORE);
const req = store.getAll();
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
async function deleteFromOutbox(id) {
const db = await openOutbox();
return new Promise((resolve, reject) => {
const tx = db.transaction(DB_STORE, 'readwrite');
tx.objectStore(DB_STORE).delete(id);
tx.oncomplete = resolve;
tx.onerror = () => reject(tx.error);
});
}
// Network-first for GETs (simplified)
self.addEventListener('fetch', event => {
const { request } = event;
if (request.method === 'GET') {
event.respondWith(
fetch(request).catch(() => caches.match(request))
);
return;
}
// Handle Like POSTs
if (request.method === 'POST' && new URL(request.url).pathname === '/api/likes') {
event.respondWith(handleLike(request));
}
});
async function handleLike(request) {
const reqClone = request.clone();
try {
// Try network first
const resp = await fetch(request);
return resp;
} catch (err) {
// Probably offline; queue the request
const body = await reqClone.json().catch(() => null);
await addToOutbox({
url: reqClone.url,
method: reqClone.method,
headers: [...reqClone.headers], // array of [key, value]
body,
timestamp: Date.now()
});
// Register a sync to replay later
if ('sync' in self.registration) {
await self.registration.sync.register(SYNC_TAG);
}
// Return a synthetic response so your app can update UI optimistically
return new Response(
JSON.stringify({ queued: true }),
{ status: 202, headers: { 'Content-Type': 'application/json' } }
);
}
}
// Background sync handler
self.addEventListener('sync', event => {
if (event.tag === SYNC_TAG) {
event.waitUntil(replayLikes());
}
});
async function replayLikes() {
const queued = await getAllFromOutbox();
for (const entry of queued) {
const { id, url, method, headers, body } = entry;
try {
const resp = await fetch(url, {
method,
headers: headers ? new Headers(headers) : undefined,
body: body ? JSON.stringify(body) : undefined,
credentials: 'include'
});
if (resp.status === 409) {
// Conflict handling: decide whether to drop, retry, or reconcile
// For a "like" action, you might just drop if the server says it's already liked
await deleteFromOutbox(id);
// Optionally notify clients about the conflict
notifyClients({ type: 'like-conflict', payload: { url, body } });
} else if (resp.ok) {
// Success: remove from outbox
await deleteFromOutbox(id);
} else {
// Non-OK, non-409 response: leave in queue to retry later
continue;
}
} catch (err) {
// Still offline or network error: abort loop, we'll retry on next sync
break;
}
}
}
// Optional: notify open tabs about conflicts or flush status
async function notifyClients(message) {
const allClients = await self.clients.matchAll({ includeUncontrolled: true });
for (const client of allClients) {
client.postMessage(message);
}
}
A few notes:
The handleLike function attempts the network; if it fails (offline), it serializes the request into a storable form (URL, method, headers, body) and writes it to IndexedDB, then registers a sync with a known tag.
The sync event will fire when the browser detects connectivity. replayLikes drains the queue in order, re‑sending each POST. On success, the entry is deleted. On 409 Conflict you can decide your own policy; the code above drops the entry and optionally notifies clients so you can update UI accordingly.
If Background Sync isn’t available in the current browser, you can also listen for online in your page and call a replayLikes equivalent via postMessage to the SW.
In your page script you don’t need to do anything special beyond registering the service worker; the SW registers its own sync when it queues a request. If you want to be explicit from the page, you can also register the sync after a failed POST:
js
navigator.serviceWorker.ready.then(reg => {
if ('sync' in reg) {
reg.sync.register('replay-likes');
}
});
Adjust the URL/path check and conflict handling to match your API semantics. The same pattern works for other POST actions you want to queue.