---
title: "How do you handle offline data sync using IndexedDB?"  
description: "How do you handle offline data sync using IndexedDB?"  
author: "ICSM Computer"  
published: 2025-06-30  
updated: 2025-06-30  
canonical: https://www.mindstick.com/interview/34298/how-do-you-handle-offline-data-sync-using-indexeddb  
category: "database"  
tags: ["database", "indexeddb"]  
reading_time: 4 minutes  

---

# How do you handle offline data sync using IndexedDB?

Handling **offline data sync with IndexedDB** involves storing user actions or data locally when the app is offline, and then syncing it with a remote server once the device comes back online.

## Strategy for Offline Data Sync

### 1. Save Data Locally When Offline

Use `navigator.onLine` or a `try/catch` around network requests to detect offline status.

```javascript
if (!navigator.onLine) {
    await saveToIndexedDB('SyncStore', { type: 'CREATE', data: myData });
} else {
    await sendToServer(myData);
}
```

### 2. Detect Online Status

Listen for the `online` event:

```javascript
window.addEventListener('online', syncOfflineData);
```

### 3. Save Data to IndexedDB (Sync Queue)

```javascript
function saveToIndexedDB(storeName, data) {
    return new Promise((resolve, reject) => {
        const request = indexedDB.open('OfflineDB', 1);
        request.onupgradeneeded = (e) => {
            const db = e.target.result;
            if (!db.objectStoreNames.contains(storeName)) {
                db.createObjectStore(storeName, { autoIncrement: true });
            }
        };

        request.onsuccess = () => {
            const db = request.result;
            const tx = db.transaction(storeName, 'readwrite');
            const store = tx.objectStore(storeName);
            store.add(data);
            tx.oncomplete = () => resolve();
            tx.onerror = () => reject('Error storing data offline');
        };

        request.onerror = () => reject('DB open error');
    });
}
```

### 4. Sync Data When Back Online

```javascript
async function syncOfflineData() {
    const db = await openIndexedDB('OfflineDB', 'SyncStore');
    const tx = db.transaction('SyncStore', 'readwrite');
    const store = tx.objectStore('SyncStore');

    const allData = await new Promise((resolve, reject) => {
        const req = store.getAll();
        req.onsuccess = () => resolve(req.result);
        req.onerror = () => reject(req.error);
    });

    for (const item of allData) {
        try {
            await sendToServer(item.data); // implement this to hit your API
            store.delete(item.id); // cleanup after successful sync
        } catch (err) {
            console.error('Sync failed for item:', item);
        }
    }
}
```

### 5. Combine It All

```javascript
window.addEventListener('load', () => {
    if (navigator.onLine) syncOfflineData();
});
window.addEventListener('online', syncOfflineData);
```

## Optional Enhancements

| Feature | Description |
| --- | --- |
| `idb` **library** | Use [Jake Archibald’s `idb`](https://github.com/jakearchibald/idb) wrapper for cleaner syntax. |
| **Service Worker** | Intercept network requests and manage caching/sync via `Background Sync`. |
| **Timestamps** | Track when data was created offline. |
| **Retry logic** | Re-attempt failed syncs with exponential backoff. |

## Summary

- Store failed requests/data in IndexedDB when offline.
- Use the `online` event to detect reconnection.
- Sync the offline queue to your server and remove synced items.
- Make syncing safe and idempotent on the server side.

## Answers

### Answer by ICSM Computer

Handling **offline data sync with IndexedDB** involves storing user actions or data locally when the app is offline, and then syncing it with a remote server once the device comes back online.

## Strategy for Offline Data Sync

### 1. Save Data Locally When Offline

Use `navigator.onLine` or a `try/catch` around network requests to detect offline status.

```javascript
if (!navigator.onLine) {
    await saveToIndexedDB('SyncStore', { type: 'CREATE', data: myData });
} else {
    await sendToServer(myData);
}
```

### 2. Detect Online Status

Listen for the `online` event:

```javascript
window.addEventListener('online', syncOfflineData);
```

### 3. Save Data to IndexedDB (Sync Queue)

```javascript
function saveToIndexedDB(storeName, data) {
    return new Promise((resolve, reject) => {
        const request = indexedDB.open('OfflineDB', 1);
        request.onupgradeneeded = (e) => {
            const db = e.target.result;
            if (!db.objectStoreNames.contains(storeName)) {
                db.createObjectStore(storeName, { autoIncrement: true });
            }
        };

        request.onsuccess = () => {
            const db = request.result;
            const tx = db.transaction(storeName, 'readwrite');
            const store = tx.objectStore(storeName);
            store.add(data);
            tx.oncomplete = () => resolve();
            tx.onerror = () => reject('Error storing data offline');
        };

        request.onerror = () => reject('DB open error');
    });
}
```

### 4. Sync Data When Back Online

```javascript
async function syncOfflineData() {
    const db = await openIndexedDB('OfflineDB', 'SyncStore');
    const tx = db.transaction('SyncStore', 'readwrite');
    const store = tx.objectStore('SyncStore');

    const allData = await new Promise((resolve, reject) => {
        const req = store.getAll();
        req.onsuccess = () => resolve(req.result);
        req.onerror = () => reject(req.error);
    });

    for (const item of allData) {
        try {
            await sendToServer(item.data); // implement this to hit your API
            store.delete(item.id); // cleanup after successful sync
        } catch (err) {
            console.error('Sync failed for item:', item);
        }
    }
}
```

### 5. Combine It All

```javascript
window.addEventListener('load', () => {
    if (navigator.onLine) syncOfflineData();
});
window.addEventListener('online', syncOfflineData);
```

## Optional Enhancements

| Feature | Description |
| --- | --- |
| `idb` **library** | Use [Jake Archibald’s `idb`](https://github.com/jakearchibald/idb) wrapper for cleaner syntax. |
| **Service Worker** | Intercept network requests and manage caching/sync via `Background Sync`. |
| **Timestamps** | Track when data was created offline. |
| **Retry logic** | Re-attempt failed syncs with exponential backoff. |

## Summary

- Store failed requests/data in IndexedDB when offline.
- Use the `online` event to detect reconnection.
- Sync the offline queue to your server and remove synced items.
- Make syncing safe and idempotent on the server side.


---

Original Source: https://www.mindstick.com/interview/34298/how-do-you-handle-offline-data-sync-using-indexeddb

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
