To implement offline-first data sync with IndexedDB and a remote API, follow a clear pattern:
queue, store, detect, and sync. Here's a robust and scalable approach, step-by-step:
async function syncWithServer() {
const queue = await db.syncQueue.orderBy('timestamp').toArray();
for (const q of queue) {
try {
// Post to remote API
await fetch(`/api/${q.table}/${q.operation}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(q.payload)
});
// Remove from queue if successful
await db.syncQueue.delete(q.id);
} catch (err) {
console.error("Sync failed:", err);
break; // Stop on first failure
}
}
}
Step 5: Pull Updates from Server (Optional)
To keep IndexedDB fresh:
async function pullLatest() {
const res = await fetch('/api/items');
const items = await res.json();
await db.items.clear();
await db.items.bulkPut(items);
}
Run this on:
First app load
Periodic intervals
After successful sync
Advanced Enhancements
Feature
How
Conflict resolution
Use timestamps or versioning (e.g., updatedAt)
Sync retries
Retry failed syncs with exponential backoff
Background sync (PWA)
Use Service Workers + Background Sync API
Delta sync
Send only changes, not full lists
Status UI
Show "Queued changes" or "Offline mode" indicators
Data Flow Summary
User adds data → stored in IndexedDB + syncQueue
Goes online → `syncQueue` processed and pushed to API
Server updates pulled back → `items` table updated
Tools You Can Use
Tool
Purpose
Dexie.js
Simplified IndexedDB
localForage
Unified local storage (IndexedDB fallback)
RxDB / PouchDB
Pre-built sync with CouchDB-like APIs
Workbox
Background sync + caching for PWAs
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To implement offline-first data sync with IndexedDB and a remote API, follow a clear pattern: queue, store, detect, and sync. Here's a robust and scalable approach, step-by-step:
1. Architecture Overview
2. Core Components
3. Implementation Steps
Step 1: Set Up Dexie.js (or plain IndexedDB)
items: Your main data tablesyncQueue: Holdsadd,update,deleteops while offlineStep 2: Queue Writes While Offline
Instead of calling the API directly, queue the change locally:
Step 3: Detect Online/Offline Status
Or manually:
Step 4: Sync Engine
Step 5: Pull Updates from Server (Optional)
To keep IndexedDB fresh:
Run this on:
Advanced Enhancements
updatedAt)Data Flow Summary
Tools You Can Use