MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Offline-First Sync with IndexedDB & Service Worker0%
Study Materials
JavaScript for AdvancedProgress 0%
1.1Higher-Order Functions & Currying1.2Function Composition & Pipelining1.3Memoization & Pure Functions1.4Execution Context & Call Stack Deep Dive1.5Scope Chain & Lexical Environment
18.1Architecture & State Store Design (Store Pattern)18.2Real-Time Collaborative Dashboard Engine18.3Offline-First Sync with IndexedDB & Service Worker18.4Production Bundling, Testing & Deployment
HomeTutorialsJavaScript for AdvancedOffline-First Sync with IndexedDB & Service Worker
Production Bundling, Testing & Deployment

Offline-First Sync with IndexedDB & Service Worker

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study Materials

Capstone Part 3: Offline-First Sync with IndexedDB

In modern enterprise web development, an application should never show a dinosaur game or crash when the user loses Wi-Fi. In this capstone lesson, you will build an Offline-First Synchronization Engine that persists state locally to IndexedDB, queues optimistic mutations while offline, and synchronizes with the remote cloud when the network recovers.


1. Offline-First Architecture

1 UI Action (User edits dashboard)
2 │
3 ▼
4 1. Optimistic Local Update (Instant UI feedback!)
5 2. Write to IndexedDB local database
6 3. Enqueue mutation in "Outbox" Store
7 │
8 Is Device Online?
9 ┌────────┴────────┐
10 YES NO
11 │ │
12 ▼ ▼
13 Send to Server Wait for window 'online' event!
14 │ │
15 └──────◄───────────┘

2. Implementing the Offline Sync Queue Manager

1class OfflineSyncManager {
2 constructor(db, apiEndpoint) {
3 this.db = db;
4 this.apiEndpoint = apiEndpoint;
5 this.isSyncing = false;
6 
7 this.initNetworkListeners();
8 }
9 
10 initNetworkListeners() {
11 // Listen for network restoration
12 window.addEventListener('online', () => {
13 console.log('[Network] Internet connection restored! Triggering sync...');
14 this.syncOutbox();
15 });
16 
17 window.addEventListener('offline', () => {
18 console.warn('[Network] Device went offline. Mutations queued locally.');
19 });
20 }
21 
22 // Enqueue an action to be executed remotely
23 async queueMutation(mutation) {
24 const record = {
25 id: 'mut_' + crypto.randomUUID(),
26 type: mutation.type,
27 payload: mutation.payload,
28 createdAt: Date.now(),
29 retryCount: 0
30 };
31 
32 // Save to IndexedDB 'outbox' store
33 await this.writeToStore('outbox', record);
34 
35 // If currently online, trigger sync immediately
36 if (navigator.onLine) {
37 this.syncOutbox();
38 }
39 }
40 
41 async syncOutbox() {
42 if (this.isSyncing || !navigator.onLine) return;
43 this.isSyncing = true;
44 
45 try {
46 const pendingMutations = await this.getAllFromStore('outbox');
47 console.log(`[Sync] Processing ${pendingMutations.length} pending mutations...`);
48 
49 for (const mutation of pendingMutations) {
50 try {
51 // Dispatch to remote server
52 const response = await fetch(this.apiEndpoint, {
53 method: 'POST',
54 headers: { 'Content-Type': 'application/json' },
55 body: JSON.stringify(mutation)
56 });
57 
58 if (response.ok) {
59 // Success! Remove from outbox
60 await this.deleteFromStore('outbox', mutation.id);
61 console.log(`[Sync] Mutation ${mutation.id} synced successfully.`);
62 } else if (response.status >= 400 && response.status < 500) {
63 // Client error (unrecoverable): discard to prevent outbox blocking
64 await this.deleteFromStore('outbox', mutation.id);
65 }
66 } catch (netErr) {
67 console.warn('[Sync] Network error during batch; halting sync until online.');
68 break; // Stop loop; will retry on next 'online' event
69 }
70 }
71 } finally {
72 this.isSyncing = false;
73 }
74 }
75 
76 // IndexedDB Promise Helpers
77 writeToStore(storeName, data) {
78 return new Promise((resolve, reject) => {
79 const tx = this.db.transaction([storeName], 'readwrite');
80 tx.objectStore(storeName).put(data);
81 tx.oncomplete = () => resolve();
82 tx.onerror = () => reject(tx.error);
83 });
84 }
85 
86 getAllFromStore(storeName) {
87 return new Promise((resolve, reject) => {
88 const tx = this.db.transaction([storeName], 'readonly');
89 const req = tx.objectStore(storeName).getAll();
90 req.onsuccess = () => resolve(req.result);
91 req.onerror = () => reject(req.error);
92 });
93 }
94 
95 deleteFromStore(storeName, key) {
96 return new Promise((resolve, reject) => {
97 const tx = this.db.transaction([storeName], 'readwrite');
98 tx.objectStore(storeName).delete(key);
99 tx.oncomplete = () => resolve();
100 tx.onerror = () => reject(tx.error);
101 });
102 }
103}

3. Background Sync API (PWA Standard)

Modern Service Workers support the Background Sync API, allowing the browser to wake up in the background and drain the outbox even after the user has completely closed the website:

1// Register Background Sync in Service Worker
2async function registerBackgroundSync() {
3 if ('serviceWorker' in navigator && 'SyncManager' in window) {
4 const registration = await navigator.serviceWorker.ready;
5 await registration.sync.register('outbox-sync');
6 console.log('Background Sync registered!');
7 }
8}
9 
10// Inside sw.js (Service Worker):
11self.addEventListener('sync', (event) => {
12 if (event.tag === 'outbox-sync') {
13 event.waitUntil(drainOfflineOutbox());
14 }
15});

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What is an "Optimistic UI Update"?
Question 2
What event fires on the window object when a device regains internet access?
Question 3
Why is an "Outbox" Object Store used in IndexedDB for offline synchronization?
Question 4
What is the primary benefit of the Service Worker Background Sync API?
Question 5
What should happen to a queued mutation in the outbox if the server returns HTTP 400 Bad Request?
Next Lesson

Production Bundling, Testing & Deployment

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Real-Time Collaborative Dashboard EngineProduction Bundling, Testing & Deployment

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext