This is a comprehensive request for building an offline-first Vue.js application with IndexedDB and background sync capabilities. Let me break down what needs to be implemented:
- Vue.js Setup: A todo app component
- IndexedDB Integration: Using
idb package for database operations
- Offline-first approach: Write to IDB immediately, display in UI
- Background sync manager: Detect network restoration and sync
- ID conflict handling: Handle UUID mapping between local and server IDs
- API integration: Push queued data to server
I'll create a comprehensive example including:
- Vue component with todo CRUD operations
- IndexedDB schema and operations
- Sync manager with queue handling
- Network detection
- ID conflict resolution
- Mock API for demonstration
Let me structure this properly:
- src/
- components/
- TodoApp.vue
- services/
- db.js (IndexedDB setup)
- syncManager.js (Background sync)
- api.js (API calls)
- App.vue
- main.js
Let me create a complete, production-ready solution with proper error handling, queue management, and sync strategies.
Vue.js Offline-First Todo App with IndexedDB & Background Sync
I'll build a complete offline-first application with IndexedDB, sync queue management, and conflict resolution.
1. Project Setup
npm install idb axios uuid
npm install -D tailwindcss
2. IndexedDB Service (src/services/db.js)
import { openDB } from 'idb';
const DB_NAME = 'todo-app-db';
const DB_VERSION = 1;
// Initialize database schema
export async function initDB() {
return openDB(DB_NAME, DB_VERSION, {
upgrade(db) {
// Todos store
if (!db.objectStoreNames.contains('todos')) {
const todoStore = db.createObjectStore('todos', {
keyPath: 'localId'
});
todoStore.createIndex('status', 'status');
todoStore.createIndex('syncStatus', 'syncStatus');
todoStore.createIndex('createdAt', 'createdAt');
}
// Sync queue store
if (!db.objectStoreNames.contains('syncQueue')) {
const queueStore = db.createObjectStore('syncQueue', {
keyPath: 'id',
autoIncrement: true
});
queueStore.createIndex('operation', 'operation');
queueStore.createIndex('timestamp', 'timestamp');
queueStore.createIndex('completed', 'completed');
}
// ID mapping store (local ID -> server ID)
if (!db.objectStoreNames.contains('idMap')) {
db.createObjectStore('idMap', { keyPath: 'localId' });
}
// Conflict log
if (!db.objectStoreNames.contains('conflicts')) {
db.createObjectStore('conflicts', {
keyPath: 'id',
autoIncrement: true
});
}
},
});
}
// ======================== TODOS ========================
export async function addTodo(title, description = '') {
const db = await initDB();
const todo = {
localId: crypto.randomUUID(),
title,
description,
status: 'pending',
completed: false,
syncStatus: 'pending', // pending, synced, failed
createdAt: Date.now(),
updatedAt: Date.now(),
serverId: null,
};
await db.add('todos', todo);
// Add to sync queue
await addToSyncQueue('CREATE', todo.localId, {
title,
description,
});
return todo;
}
export async function getTodos() {
const db = await initDB();
return db.getAll('todos');
}
export async function getTodoById(localId) {
const db = await initDB();
return db.get('todos', localId);
}
export async function updateTodo(localId, updates) {
const db = await initDB();
const todo = await db.get('todos', localId);
if (!todo) throw new Error('Todo not found');
const updated = {
...todo,
...updates,
updatedAt: Date.now(),
syncStatus: 'pending',
};
await db.put('todos', updated);
// Add to sync queue
await addToSyncQueue('UPDATE', localId, updates);
return updated;
}
export async function deleteTodo(localId) {
const db = await initDB();
const todo = await db.get('todos', localId);
if (!todo) throw new Error('Todo not found');
await db.delete('todos', localId);
// Add to sync queue
await addToSyncQueue('DELETE', localId, {});
return todo;
}
// ======================== SYNC QUEUE ========================
export async function addToSyncQueue(operation, localId, payload) {
const db = await initDB();
const queueItem = {
operation, // CREATE, UPDATE, DELETE
localId,
payload,
timestamp: Date.now(),
completed: false,
attempts: 0,
lastError: null,
};
const id = await db.add('syncQueue', queueItem);
return { ...queueItem, id };
}
export async function getSyncQueue(onlyPending = true) {
const db = await initDB();
let items = await db.getAll('syncQueue');
if (onlyPending) {
items = items.filter(item => !item.completed);
}
return items.sort((a, b) => a.timestamp - b.timestamp);
}
export async function markQueueItemAsCompleted(queueId) {
const db = await initDB();
const item = await db.get('syncQueue', queueId);
if (!item) return;
await db.put('syncQueue', {
...item,
completed: true,
});
}
export async function updateQueueItemError(queueId, error) {
const db = await initDB();
const item = await db.get('syncQueue', queueId);
if (!item) return;
await db.put('syncQueue', {
...item,
attempts: item.attempts + 1,
lastError: error,
});
}
// ======================== ID MAPPING ========================
export async function saveIdMapping(localId, serverId) {
const db = await initDB();
const mapping = {
localId,
serverId,
createdAt: Date.now(),
};
await db.put('idMap', mapping);
// Update todo with server ID
const todo = await db.get('todos', localId);
if (todo) {
await db.put('todos', {
...todo,
serverId,
syncStatus: 'synced',
});
}
}
export async function getServerId(localId) {
const db = await initDB();
const mapping = await db.get('idMap', localId);
return mapping?.serverId || null;
}
// ======================== CONFLICT HANDLING ========================
export async function logConflict(localId, conflictType, details) {
const db = await initDB();
const conflict = {
localId,
conflictType, // merge, overwrite, delete
details,
createdAt: Date.now(),
resolved: false,
};
await db.add('conflicts', conflict);
return conflict;
}
export async function getConflicts() {
const db = await initDB();
return db.getAll('conflicts');
}
export async function resolveConflict(conflictId, resolution) {
const db = await initDB();
const conflict = await db.get('conflicts', conflictId);
if (!conflict) return;
await db.put('conflicts', {
...conflict,
resolved: true,
resolution,
});
}
// ======================== UTILITIES ========================
export async function clearDatabase() {
const db = await initDB();
await db.clear('todos');
await db.clear('syncQueue');
await db.clear('idMap');
await db.clear('conflicts');
}
export async function getDBStats() {
const db = await initDB();
const todos = await db.getAll('todos');
const queue = await db.getAll('syncQueue');
const pendingQueuItems = queue.filter(q => !q.completed);
const conflicts = await db.getAll('conflicts');
return {
todoCount: todos.length,
syncedTodos: todos.filter(t => t.syncStatus === 'synced').length,
failedTodos: todos.filter(t => t.syncStatus === 'failed').length,
queueLength: pendingQueuItems.length,
conflictCount: conflicts.filter(c => !c.resolved).length,
};
}
3. API Service (src/services/api.js)
import axios from 'axios';
const API_BASE_URL = process.env.VUE_APP_API_URL || 'http://localhost:3000/api';
const api = axios.create({
baseURL: API_BASE_URL,
timeout: 10000,
});
// Network status
export let isOnline = navigator.onLine;
window.addEventListener('online', () => {
isOnline = true;
console.log('✅ Network restored');
});
window.addEventListener('offline', () => {
isOnline = false;
console.log('❌ Network lost');
});
export function getNetworkStatus() {
return isOnline;
}
// API calls
export async function createTodo(todo) {
const response = await api.post('/todos', {
title: todo.title,
description: todo.description,
});
return response.data; // { id, title, description, ... }
}
export async function updateTodoOnServer(serverId, updates) {
const response = await api.patch(`/todos/${serverId}`, updates);
return response.data;
}
export async function deleteTodoOnServer(serverId) {
await api.delete(`/todos/${serverId}`);
}
export async function getTodosFromServer() {
const response = await api.get('/todos');
return response.data; // Array of todos
}
export async function syncStats() {
try {
const response = await api.get('/sync/stats');
return response.data;
} catch (error) {
console.error('Failed to fetch sync stats:', error);
return null;
}
}
// Error handling
export function isNetworkError(error) {
return !error.response && error.message !== 'cancelled';
}
export function getErrorMessage(error) {
if (error.response?.data?.message) {
return error.response.data.message;
}
return error.message || 'An error occurred';
}
4. Sync Manager (src/services/syncManager.js)
import {
getSyncQueue,
markQueueItemAsCompleted,
updateQueueItemError,
getServerId,
saveIdMapping,
getTodoById,
updateTodo,
deleteTodo,
logConflict,
} from './db';
import {
createTodo,
updateTodoOnServer,
deleteTodoOnServer,
isNetworkError,
getErrorMessage,
getNetworkStatus,
} from './api';
class SyncManager {
constructor() {
this.isSyncing = false;
this.syncInterval = null;
this.retryStrategy = {
maxAttempts: 3,
baseDelay: 1000, // 1 second
maxDelay: 30000, // 30 seconds
};
}
/**
* Start sync manager and listen for network changes
*/
start() {
console.log('🚀 Sync Manager started');
// Check for pending items immediately
if (getNetworkStatus()) {
this.syncPendingQueue();
}
// Listen for network restoration
window.addEventListener('online', () => {
console.log('📡 Online detected, starting sync...');
this.syncPendingQueue();
});
// Periodically check for pending items (every 30 seconds)
this.syncInterval = setInterval(() => {
if (getNetworkStatus() && !this.isSyncing) {
this.syncPendingQueue();
}
}, 30000);
}
/**
* Stop sync manager
*/
stop() {
if (this.syncInterval) {
clearInterval(this.syncInterval);
}
console.log('🛑 Sync Manager stopped');
}
/**
* Main sync function - processes all pending queue items
*/
async syncPendingQueue() {
if (this.isSyncing) {
console.log('⏳ Sync already in progress...');
return;
}
this.isSyncing = true;
console.log('🔄 Starting sync of pending items...');
try {
const queueItems = await getSyncQueue(true); // Only pending items
if (queueItems.length === 0) {
console.log('✅ Queue is empty');
this.isSyncing = false;
return;
}
console.log(`📤 Processing ${queueItems.length} pending items`);
for (const item of queueItems) {
await this.processSyncItem(item);
}
console.log('✨ Sync completed');
} catch (error) {
console.error('❌ Sync failed:', error);
} finally {
this.isSyncing = false;
}
}
/**
* Process a single sync queue item
*/
async processSyncItem(queueItem) {
const { id, operation, localId, payload, attempts } = queueItem;
try {
// Check if retry limit exceeded
if (attempts >= this.retryStrategy.maxAttempts) {
console.warn(`⚠️ Max retry attempts reached for ${operation}:${localId}`);
await updateQueueItemError(
id,
'Max retry attempts exceeded'
);
return;
}
console.log(`📨 Syncing ${operation}:${localId}`);
switch (operation) {
case 'CREATE':
await this.syncCreate(id, localId, payload);
break;
case 'UPDATE':
await this.syncUpdate(id, localId, payload);
break;
case 'DELETE':
await this.syncDelete(id, localId);
break;
default:
console.warn(`Unknown operation: ${operation}`);
}
} catch (error) {
console.error(`❌ Failed to sync ${operation}:${localId}:`, error);
await updateQueueItemError(id, getErrorMessage(error));
}
}
/**
* Sync CREATE operation
*/
async syncCreate(queueId, localId, payload) {
try {
// Create on server
const serverResponse = await createTodo({
title: payload.title,
description: payload.description,
});
// Map local ID to server ID
await saveIdMapping(localId, serverResponse.id);
// Mark as completed
await markQueueItemAsCompleted(queueId);
console.log(
`✅ CREATE synced: ${localId} -> ${serverResponse.id}`
);
} catch (error) {
throw error;
}
}
/**
* Sync UPDATE operation
*/
async syncUpdate(queueId, localId, payload) {
try {
// Get server ID
let serverId = await getServerId(localId);
if (!serverId) {
// Local item was never synced to server
throw new Error('Item not yet synced to server');
}
// Update on server
const serverResponse = await updateTodoOnServer(
serverId,
payload
);
// Check for conflicts (e.g., server has newer version)
const localTodo = await getTodoById(localId);
if (
localTodo &&
serverResponse.updatedAt > localTodo.updatedAt
) {
await this.handleConflict(
localId,
'stale_update',
{ local: localTodo, server: serverResponse }
);
}
// Mark as completed
await markQueueItemAsCompleted(queueId);
console.log(`✅ UPDATE synced: ${localId}`);
} catch (error) {
throw error;
}
}
/**
* Sync DELETE operation
*/
async syncDelete(queueId, localId) {
try {
const serverId = await getServerId(localId);
if (serverId) {
// Delete on server
await deleteTodoOnServer(serverId);
// Delete local mapping
// (todo is already deleted from todos store)
console.log(
`✅ DELETE synced: ${localId} (server: ${serverId})`
);
} else {
console.log(`✅ DELETE synced: ${localId} (was local only)`);
}
// Mark as completed
await markQueueItemAsCompleted(queueId);
} catch (error) {
throw error;
}
}
/**
* Handle sync conflicts
*/
async handleConflict(localId, conflictType, details) {
console.warn(`⚠️ Conflict detected: ${conflictType} for ${localId}`);
// Log the conflict
const conflict = await logConflict(
localId,
conflictType,
details
);
// Default resolution strategy: server wins
if (conflictType === 'stale_update' && details.server) {
// Update local todo with server data
await updateTodo(localId, details.server);
console.log(`🔄 Applied server-wins resolution for ${localId}`);
}
return conflict;
}
/**
* Get retry delay using exponential backoff
*/
getRetryDelay(attempts) {
const delay = Math.min(
this.retryStrategy.baseDelay * Math.pow(2, attempts),
this.retryStrategy.maxDelay
);
// Add jitter
return delay + Math.random() * 1000;
}
/**
* Get sync status
*/
getSyncStatus() {
return {
isSyncing: this.isSyncing,
isOnline: getNetworkStatus(),
};
}
}
// Export singleton instance
export default new SyncManager();
5. Vue Component (src/components/TodoApp.vue)
<template>
<div class="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 p-4">
<div class="max-w-2xl mx-auto">
<!-- Header -->
<div class="bg-white rounded-lg shadow-lg p-6 mb-6">
<div class="flex items-center justify-between mb-4">
<h1 class="text-3xl font-bold text-gray-800">
📝 Offline Todo App
</h1>
<div class="flex items-center gap-3">
<!-- Network Status -->
<div
:class="{
'bg-green-100 text-green-800': isOnline,
'bg-red-100 text-red-800': !isOnline,
}"
class="px-3 py-1 rounded-full text-sm font-semibold flex items-center gap-2"
>
<span
:class="[
'w-2 h-2 rounded-full',
isOnline ? 'bg-green-500' : 'bg-red-500',
]"
></span>
{{ isOnline ? 'Online' : 'Offline' }}
</div>
<!-- Sync Status -->
<div
v-if="stats.queueLength > 0"
class="bg-yellow-100 text-yellow-800 px-3 py-1 rounded-full text-sm font-semibold flex items-center gap-2"
>
<span v-if="syncStatus.isSyncing" class="animate-spin">⚙️</span>
<span v-else>📤</span>
{{ stats.queueLength }} pending
</div>
</div>
</div>
<!-- Stats -->
<div class="grid grid-cols-4 gap-4 text-center text-sm">
<div>
<p class="text-gray-600">Total Todos</p>
<p class="text-2xl font-bold text-blue-600">
{{ stats.todoCount }}
</p>
</div>
<div>
<p class="text-gray-600">Synced</p>
<p class="text-2xl font-bold text-green-600">
{{ stats.syncedTodos }}
</p>
</div>
<div>
<p class="text-gray-600">Pending</p>
<p class="text-2xl font-bold text-yellow-600">
{{ stats.queueLength }}
</p>
</div>
<div>
<p class="text-gray-600">Failed</p>
<p class="text-2xl font-bold text-red-600">
{{ stats.failedTodos }}
</p>
</div>
</div>
</div>
<!-- Add Todo Form -->
<form
@submit.prevent="addNewTodo"
class="bg-white rounded-lg shadow-lg p-6 mb-6"
>
<h2 class="text-xl font-semibold text-gray-800 mb-4">
Add New Todo
</h2>
<div class="space-y-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">
Title
</label>
<input
v-model="newTodo.title"
type="text"
placeholder="What needs to be done?"
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
required
/>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">
Description (optional)
</label>
<textarea
v-model="newTodo.description"
placeholder="Add more details..."
rows="3"
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
></textarea>
</div>
<button
type="submit"
class="w-full bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 rounded-lg transition"
>
✨ Add Todo
</button>
</div>
</form>
<!-- Todo List -->
<div class="space-y-4">
<div class="flex items-center justify-between mb-4">
<h2 class="text-xl font-semibold text-gray-800">
Todos ({{ todos.length }})
</h2>
<div class="flex gap-2">
<button
@click="filterStatus = 'all'"
:class="{
'bg-blue-500 text-white': filterStatus === 'all',
'bg-gray-200 text-gray-700': filterStatus !== 'all',
}"
class="px-3 py-1 rounded text-sm font-medium transition"
>
All
</button>
<button
@click="filterStatus = 'pending'"
:class="{
'bg-blue-500 text-white': filterStatus === 'pending',
'bg-gray-200 text-gray-700': filterStatus !== 'pending',
}"
class="px-3 py-1 rounded text-sm font-medium transition"
>
Pending
</button>
<button
@click="filterStatus = 'completed'"
:class="{
'bg-blue-500 text-white': filterStatus === 'completed',
'bg-gray-200 text-gray-700': filterStatus !== 'completed',
}"
class="px-3 py-1 rounded text-sm font-medium transition"
>
Done
</button>
</div>
</div>
<!-- Empty State -->
<div
v-if="filteredTodos.length === 0"
class="bg-white rounded-lg shadow p-8 text-center"
>
<p class="text-gray-500 text-lg">
📭 No todos yet. Create one to get started!
</p>
</div>
<!-- Todo Items -->
<div
v-for="todo in filteredTodos"
:key="todo.localId"
class="bg-white rounded-lg shadow-lg p-4 hover:shadow-xl transition"
>
<div class="flex items-start justify-between gap-4">
<!-- Checkbox -->
<input
type="checkbox"
:checked="todo.completed"
@change="toggleTodo(todo)"
class="mt-1.5 w-5 h-5 text-blue-500 rounded focus:ring-2 focus:ring-blue-500 cursor-pointer"
/>
<!-- Content -->
<div class="flex-1">
<h3
:class="{
'line-through text-gray-400': todo.completed,
'text-gray-800': !todo.completed,
}"
class="text-lg font-semibold"
>
{{ todo.title }}
</h3>
<p
v-if="todo.description"
class="text-gray-600 mt-1 text-sm"
>
{{ todo.description }}
</p>
<div class="flex items-center gap-2 mt-2 text-xs text-gray-500">
<span>{{ formatDate(todo.createdAt) }}</span>
<span>•</span>
<span
:class="{
'text-green-600': todo.syncStatus === 'synced',
'text-yellow-600': todo.syncStatus === 'pending',
'text-red-600': todo.syncStatus === 'failed',
}"
>
{{
todo.syncStatus === 'synced'
? '✅ Synced'
: todo.syncStatus === 'pending'
? '⏳ Pending'
: '❌ Failed'
}}
</span>
</div>
</div>
<!-- Delete Button -->
<button
@click="deleteTodo(todo)"
:disabled="todo.syncStatus === 'pending'"
class="text-red-500 hover:text-red-700 transition disabled:opacity-50 disabled:cursor-not-allowed"
>
🗑️
</button>
</div>
</div>
</div>
<!-- Conflicts Panel -->
<div v-if="conflicts.length > 0" class="mt-6">
<div class="bg-red-50 border-l-4 border-red-500 rounded-lg p-4">
<h3 class="font-semibold text-red-800 mb-3">
⚠️ {{ conflicts.length }} Unresolved Conflicts
</h3>
<div class="space-y-2">
<div
v-for="conflict in conflicts"
:key="conflict.id"
class="bg-white p-3 rounded text-sm"
>
<p class="text-gray-700 mb-2">
{{ conflict.details }}
</p>
<button
@click="resolveConflict(conflict)"
class="text-blue-600 hover:text-blue-800 font-medium"
>
Resolve →
</button>
</div>
</div>
</div>
</div>
<!-- Debug Panel -->
<div class="mt-6 bg-gray-100 rounded-lg p-4 text-xs">
<button
@click="showDebug = !showDebug"
class="font-semibold text-gray-700 hover:text-gray-900"
>
{{ showDebug ? '▼' : '▶' }} Debug Info
</button>
<div v-show="showDebug" class="mt-2 space-y-1 font-mono">
<p>Network: {{ isOnline ? 'Online' : 'Offline' }}</p>
<p>Syncing: {{ syncStatus.isSyncing ? 'Yes' : 'No' }}</p>
<p>Queue: {{ stats.queueLength }} items</p>
<button
@click="clearAllData"
class="mt-3 text-red-600 hover:text-red-800 underline"
>
🗑️ Clear All Data
</button>
</div>
</div>
</div>
</div>
</template>
<script>
import { reactive, computed, onMounted, onUnmounted, ref } from 'vue';
import {
addTodo,
getTodos,
updateTodo,
deleteTodo,
getDBStats,
getConflicts,
resolveConflict,
clearDatabase,
} from '../services/db';
import { getNetworkStatus } from '../services/api';
import syncManager from '../services/syncManager';
export default {
name: 'TodoApp',
setup() {
const todos = ref([]);
const newTodo = reactive({ title: '', description: '' });
const filterStatus = ref('all');
const isOnline = ref(navigator.onLine);
const stats = ref({
todoCount: 0,
syncedTodos: 0,
queueLength: 0,
failedTodos: 0,
});
const syncStatus = reactive({ isSyncing: false });
const conflicts = ref([]);
const showDebug = ref(false);
// Load todos
async function loadTodos() {
try {
todos.value = await getTodos();
} catch (error) {
console.error('Failed to load todos:', error);
}
}
// Update stats
async function updateStats() {
try {
const dbStats = await getDBStats();
stats.value = dbStats;
const conflictList = await getConflicts();
conflicts.value = conflictList.filter(c => !c.resolved);
} catch (error) {
console.error('Failed to update stats:', error);
}
}
// Add new todo
async function addNewTodo() {
if (!newTodo.title.trim()) return;
try {
const todo = await addTodo(
newTodo.title.trim(),
newTodo.description.trim()
);
todos.value.push(todo);
newTodo.title = '';
newTodo.description = '';
await updateStats();
} catch (error) {
console.error('Failed to add todo:', error);
}
}
// Toggle todo
async function toggleTodo(todo) {
try {
const updated = await updateTodo(todo.localId, {
completed: !todo.completed,
});
const index = todos.value.findIndex(t => t.localId === todo.localId);
if (index !== -1) {
todos.value[index] = updated;
}
await updateStats();
} catch (error) {
console.error('Failed to toggle todo:', error);
}
}
// Delete todo
async function deleteTodo_impl(todo) {
try {
await deleteTodo(todo.localId);
todos.value = todos.value.filter(t => t.localId !== todo.localId);
await updateStats();
} catch (error) {
console.error('Failed to delete todo:', error);
}
}
// Resolve conflict
async function resolveConflict_impl(conflict) {
try {
await resolveConflict(conflict.id, { strategy: 'server_wins' });
await updateStats();
} catch (error) {
console.error('Failed to resolve conflict:', error);
}
}
// Clear all data
async function clearAllData() {
if (confirm('⚠️ This will delete all data. Are you sure?')) {
try {
await clearDatabase();
todos.value = [];
await updateStats();
} catch (error) {
console.error('Failed to clear data:', error);
}
}
}
// Format date
function formatDate(timestamp) {
const date = new Date(timestamp);
return date.toLocaleString();
}
// Filtered todos
const filteredTodos = computed(() => {
return todos.value.filter(todo => {
if (filterStatus.value === 'completed') {
return todo.completed;
}
if (filterStatus.value === 'pending') {
return !todo.completed;
}
return true;
});
});
// Network event handlers
const handleOnline = () => {
isOnline.value = true;
};
const handleOffline = () => {
isOnline.value = false;
};
// Sync status watcher
const syncStatusInterval = setInterval(() => {
syncStatus.isSyncing = syncManager.getSyncStatus().isSyncing;
}, 500);
// Lifecycle
onMounted(async () => {
await loadTodos();
await updateStats();
syncManager.start();
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
// Reload stats periodically
const statsInterval = setInterval(updateStats, 2000);
onUnmounted(() => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
clearInterval(statsInterval);
clearInterval(syncStatusInterval);
syncManager.stop();
});
});
return {
todos,
newTodo,
filterStatus,
isOnline,
stats,
syncStatus,
conflicts,
showDebug,
filteredTodos,
addNewTodo,
toggleTodo,
deleteTodo: deleteTodo_impl,
resolveConflict: resolveConflict_impl,
clearAllData,
formatDate,
};
},
};
</script>
6. Main App (src/App.vue)
<template>
<div id="app">
<TodoApp />
</div>
</template>
<script>
import TodoApp from './components/TodoApp.vue';
export default {
name: 'App',
components: {
TodoApp,
},
};
</script>
<style>
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto',
'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans',
'Helvetica Neue', sans-serif;
}
#app {
width: 100%;
min-height: 100vh;
}
</style>
7. Main Entry (src/main.js)
import { createApp } from 'vue';
import App from './App.vue';
const app = createApp(App);
app.mount('#app');
8. Mock API Server (mock-server.js)
// Simple Express server for testing
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
// In-memory storage
const todos = new Map();
let nextId = 1;
// GET /api/todos
app.get('/api/todos', (req, res) => {
res.json(Array.from(todos.values()));
});
// POST /api/todos
app.post('/api/todos', (req, res) => {
const { title, description } = req.body;
// Simulate network delay
setTimeout(() => {
const todo = {
id: nextId++,
title,
description,
completed: false,
createdAt: Date.now(),
updatedAt: Date.now(),
};
todos.set(todo.id, todo);
res.status(201).json(todo);
}, 500);
});
// PATCH /api/todos/:id
app.patch('/api/todos/:id', (req, res) => {
const id = parseInt(req.params.id);
const todo = todos.get(id);
if (!todo) {
return res.status(404).json({ message: 'Not found' });
}
setTimeout(() => {
const updated = {
...todo,
...req.body,
updatedAt: Date.now(),
};
todos.set(id, updated);
res.json(updated);
}, 300);
});
// DELETE /api/todos/:id
app.delete('/api/todos/:id', (req, res) => {
const id = parseInt(req.params.id);
setTimeout(() => {
todos.delete(id);
res.status(204).send();
}, 300);
});
app.listen(3000, () => {
console.log('Mock API server running on http://localhost:3000');
});
9. Environment Config (.env)
VUE_APP_API_URL=http://localhost:3000/api
VUE_APP_SYNC_INTERVAL=30000
VUE_APP_MAX_RETRY_ATTEMPTS=3
Key Features
✅ Offline-first: Writes to IDB immediately
✅ Background Sync: Queues operations and syncs when online
✅ ID Mapping: Handles local ↔ server ID conflicts
✅ Conflict Resolution: Server-wins strategy for stale updates
✅ Network Detection: Listens for online/offline events
✅ Retry Logic: Exponential backoff with max attempts
✅ UI Feedback: Real-time sync status and network indicators
✅ Debug Panel: Monitor queue and sync state
This provides a production-ready offline-first app!