Outlining complete Vue.js offline-first app with idb
The plan details a full solution using idb for IndexedDB with separate stores for todos and a sync queue, plus a background sync manager triggered on network restoration to push queued changes and handle ID conflicts by mapping temporary client IDs to server-assigned ones. Next, I'll produce the final structured code and explanations reflecting this approach.
Below is a minimal example of how you can set up a Vue.js offline‑first Todo app using idb (the IndexedDB promise wrapper) to store todos locally, immediately show them in the UI, and then synchronize when the network is restored. It includes:
- IndexedDB setup for local persistence of todos and a “pending sync queue”.
- Vue component demonstrating adding todos.
- Sync manager that listens for
online events and flushes queued items to the server.
- Server conflict handling (renaming temporary IDs to server‑assigned IDs, updating the local DB).
Note: This is an illustrative example, not production‑ready code. You’ll want to add error handling, security, authentication, etc., in a real app. Also, “Background Sync” can be implemented via a Service Worker registration if you’re targeting browsers that support it. Here we use a simpler online event approach.
1) Install Dependencies
npm install idb
# or
yarn add idb
2) IndexedDB Setup (db.js)
Create a module to initialize and export your IndexedDB connection using idb. It holds two object stores:
todos for the local list of todos
syncQueue for operations to retry once back online
// db.js
import { openDB } from 'idb';
export const DB_NAME = 'offline-todo-db';
export const DB_VERSION = 1;
export const STORES = {
TODOS: 'todos',
SYNC_QUEUE: 'syncQueue'
};
export async function initDB() {
return openDB(DB_NAME, DB_VERSION, {
upgrade(db) {
if (!db.objectStoreNames.contains(STORES.TODOS)) {
db.createObjectStore(STORES.TODOS, { keyPath: 'id' });
}
if (!db.objectStoreNames.contains(STORES.SYNC_QUEUE)) {
db.createObjectStore(STORES.SYNC_QUEUE, {
keyPath: 'queueId',
autoIncrement: true
});
}
}
});
}
3) IndexedDB Helper Functions (dbHelpers.js)
A few helper functions to abstract adding, reading, and clearing items:
// dbHelpers.js
import { initDB, STORES } from './db';
export async function getAllTodos() {
const db = await initDB();
return db.getAll(STORES.TODOS);
}
export async function putTodo(todo) {
const db = await initDB();
return db.put(STORES.TODOS, todo);
}
export async function putTodos(todos) {
const db = await initDB();
const tx = db.transaction(STORES.TODOS, 'readwrite');
for (const todo of todos) {
tx.store.put(todo);
}
await tx.done;
}
export async function deleteTodo(id) {
const db = await initDB();
return db.delete(STORES.TODOS, id);
}
export async function addToSyncQueue(entry) {
const db = await initDB();
return db.add(STORES.SYNC_QUEUE, entry);
}
export async function getSyncQueue() {
const db = await initDB();
return db.getAll(STORES.SYNC_QUEUE);
}
export async function clearSyncQueueItem(queueId) {
const db = await initDB();
return db.delete(STORES.SYNC_QUEUE, queueId);
}
4) API Service (todoService.js)
A simple service to POST todos to a server. The server is assumed to return { id: newServerId } for new entries. If the server requires a client-provided clientId, you can pass that as well for deduplication.
// todoService.js
const API_URL = 'https://example.com/api/todos';
// POST a new todo to the server
export async function createTodoOnServer(todo) {
// Adjust request to your actual API contract
const response = await fetch(API_URL, {
method: 'POST',
body: JSON.stringify(todo),
headers: { 'Content-Type': 'application/json' }
});
if (!response.ok) {
const errText = await response.text();
throw new Error(`Server error: ${response.status} - ${errText}`);
}
// Suppose the server returns { id: "12345" }
return response.json();
}
5) Sync Manager (syncManager.js)
Listens for online events (or could be triggered by a Service Worker background sync). It retrieves queued entries from IndexedDB and attempts to push them to the server. If the server returns a new ID, we update the local todo accordingly. If there’s an ID conflict, we can rename the local ID to the server’s ID and proceed.
// syncManager.js
import {
getSyncQueue,
clearSyncQueueItem,
putTodo,
deleteTodo
} from './dbHelpers';
import { createTodoOnServer } from './todoService';
// Attempt to sync a single queue item
async function processQueueItem(item) {
if (item.type === 'CREATE') {
// Post to server
const serverResp = await createTodoOnServer(item.payload);
// Suppose serverResp = { id: "<server-generated-id>" }
// Update the local todo with the new server id
const updatedTodo = {
...item.payload,
id: serverResp.id,
synced: true
};
// The old local ID might be something like a UUID or negative number
await deleteTodo(item.payload.id);
await putTodo(updatedTodo);
}
}
// Main sync function to process all queue items
export async function syncQueue() {
const queue = await getSyncQueue();
for (const item of queue) {
try {
await processQueueItem(item);
// Remove from queue if successful
await clearSyncQueueItem(item.queueId);
} catch (err) {
console.error(`Sync failed for queueId=${item.queueId}:`, err);
// If you want to break on first failure, you can do so,
// or keep retrying the next items
}
}
}
// Automatically sync when online
window.addEventListener('online', () => {
syncQueue().catch(err => console.error('Sync error:', err));
});
Handling ID Conflicts:
The example above handles the typical case where the server assigns a new ID to the todo. If the server returns an error because the client tried to use an existing ID, the code should parse that error (like HTTP 409), generate a new temporary ID or reuse the server’s ID, and reconcile the local record accordingly. The snippet shows a path: “delete the old local todo by temp ID, then put the updated todo with server ID.”
6) Vue App (App.vue)
A simple Vue SFC that displays the current list of todos from IndexedDB, lets you add a new todo offline, and immediately stores it locally and in the queue for later syncing.
<!-- App.vue -->
<template>
<div class="app">
<h1>Offline-First Todos</h1>
<form @submit.prevent="addTodo">
<input
v-model="newTodoText"
placeholder="What needs to be done?"
required
/>
<button type="submit">Add Todo</button>
</form>
<p v-if="!onlineStatus" style="color: red;">You are offline. New items will sync later.</p>
<ul>
<li v-for="todo in todos" :key="todo.id">
<strong v-if="!todo.synced" style="color: orange;">(pending)</strong>
{{ todo.text }}
</li>
</ul>
</div>
</template>
<script>
import { onMounted, reactive, ref } from 'vue';
import { v4 as uuidv4 } from 'uuid'; // optional, or use any ID generator
import {
getAllTodos,
putTodo,
addToSyncQueue,
} from './dbHelpers';
import { syncQueue } from './syncManager';
export default {
name: 'App',
setup() {
const todos = reactive([]);
const newTodoText = ref('');
const onlineStatus = ref(navigator.onLine);
// Refresh the local list from IndexedDB
async function loadTodos() {
const all = await getAllTodos();
todos.splice(0, todos.length, ...all);
}
async function addTodo() {
// Generate a temporary local ID
const tempId = uuidv4();
const todo = {
id: tempId,
text: newTodoText.value,
createdAt: new Date().toISOString(),
synced: false
};
// 1) Write to IDB immediately (so it shows in UI)
await putTodo(todo);
// 2) Add this creation to the sync queue
await addToSyncQueue({
type: 'CREATE',
payload: todo
});
newTodoText.value = '';
await loadTodos();
// Optionally, attempt immediate sync if online
if (navigator.onLine) {
await syncQueue();
await loadTodos();
}
}
function updateOnlineStatus() {
onlineStatus.value = navigator.onLine;
}
onMounted(async () => {
await loadTodos();
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);
});
return {
todos,
newTodoText,
addTodo,
onlineStatus
};
}
};
</script>
<style scoped>
.app {
padding: 1rem;
font-family: Arial, sans-serif;
}
form {
margin-bottom: 1rem;
}
</style>
7) Vue Entry Point (main.js)
Just a standard Vue entry file:
// main.js
import { createApp } from 'vue';
import App from './App.vue';
// Optional polyfills if targeting older browsers
// import 'core-js/stable';
// import 'regenerator-runtime/runtime';
createApp(App).mount('#app');
8) Background Sync (Optional) via Service Worker
If you want to add true “background sync,” you can register a Service Worker and use the Background Sync API. Roughly:
// service-worker.js
self.addEventListener('sync', event => {
if (event.tag === 'sync-todos') {
event.waitUntil(
// call your syncQueue() or similar logic from within the SW
);
}
});
Then in your app:
navigator.serviceWorker.ready.then(reg => {
if ('sync' in reg) {
reg.sync.register('sync-todos');
}
});
You’ll need to ensure your sync logic is also accessible in the worker context (which typically requires different packaging or messaging), so many developers just use the online event approach shown above for simpler setups.
How ID Conflicts Are Handled
- Temporary IDs: The UI uses a client-generated
tempId so that the user sees the todo immediately.
- Server Returns a New ID: After sending the todo to the server, the server replies with a canonical ID. The sync logic:
- Deletes the temporary local record.
- Re-inserts it with the server ID.
- Server Reports Conflict (e.g., 409): You can catch that error in
createTodoOnServer, generate a new ID or fetch the existing record from the server, and decide how to merge or discard. The code above demonstrates the pattern to replace the temporary ID with the server’s ID.
Summary
- Create: User adds a todo → Stored in IDB & shown immediately.
- Offline: The app continues storing new todos locally + puts them in a
syncQueue.
- Online: On
online event or manual sync, the app processes syncQueue, posting pending todos to the server, reconciling IDs, and marking them synced locally.
- Conflict: Temporary IDs avoid collisions; real IDs come from the server, and conflicts can be resolved by adopting the server ID and updating local records.
This approach gives you a solid starting point for an offline-first Vue.js Todo app that uses IndexedDB via idb, with background synchronization and basic ID conflict handling.