Framing the Offline Sync
I've been carefully defining the core objective: a Vue.js app with both offline editing capabilities and seamless server synchronization when a connection becomes available. I'm now zeroing in on the best local storage options to achieve this offline data persistence.
Considering Database Choices
I've decided to use idb for IndexedDB interactions, preferring its lighter footprint. My frontend will utilize Vue 3 with composables for simplicity, managing local data via IndexedDB. Sync logic will manage CRUD operations and queue changes offline, processing them when online.
Planning Offline Simulation
I'm now focusing on simulating the server interactions. I'll use setTimeout and promises to mimic network behavior and error conditions. This includes defining a structure for the sync queue, which will hold operation types and their data to be processed when online. My data model is simplified to a "Note" structure, keeping track of its state and update timestamp.
Developing Sync Logic
Currently, I'm focusing on the sync strategy. The plan is to write to IndexedDB, then attempt API sync. Offline, I'll catch errors and queue retries on online events. I've decided to install idb for clearer IndexedDB interactions. I'm now exploring the optimal data structure, debating between a separate queue store or a simple synced flag for each note. For this project, I'm leaning towards the simpler, synced flag.
Prioritizing the Queue Pattern
I'm now implementing the Queue Pattern, as it offers a cleaner approach to managing offline CRUD operations. I've concluded that a dedicated syncQueue store in idb is essential. This handles additions, modifications, and deletions in a more robust way, especially when considering network interruptions. The src/db.js file is set to manage IndexedDB interactions and the sync queue. My focus is now shifting toward the Vue component, which will interact with this database and react to online/offline status changes. I'll need to define a watcher for navigator.onLine and construct a function that processes the sync queue, interacting with a mock API that simulates server responses.
Updating UI Elements
My current focus is improving the user interface. I'm adding visual cues like an online/offline badge and indicators for pending sync items. I've also simplified conflict resolution using a Last-Write-Wins strategy locally and an Append-Only sync log. I've started using crypto.randomUUID() for immediate client-side ID generation. Furthermore, I'm now polishing the final implementation with detailed code comments and clear running instructions. I've chosen a To-Do List application as the example.
Creating Core Project Structure
I'm now starting on the core structure of the project, focusing on a minimal "Hello World" application that demonstrates offline synchronization. I'm writing up setup instructions, developing db.js for IndexedDB interaction, and building the App.vue component to encapsulate the application's logic and user interface. I also plan to describe the Offline-First strategy I've adopted in this setup.
This is a complex architectural pattern known as "Offline-First." To build this in Vue.js, we need three main layers:
- The Local Database (IndexedDB): The single source of truth for the UI.
- The Sync Manager: Watches network status and creates a queue of changes to send to the server.
- The UI: Reacts to local data immediately (Optimistic UI).
We will use the idb library (a lightweight wrapper by Google) to make IndexedDB easier to use.
Prerequisites
Create a Vue project and install the idb library:
npm create vue@latest my-offline-app
cd my-offline-app
npm install idb
npm run dev
1. The Database Layer (src/db.js)
We will create two object stores in IndexedDB:
tasks: Stores the actual data to show in the UI.
syncQueue: Stores operations (add/edit/delete) that haven't reached the server yet.
// src/db.js
import { openDB } from 'idb';
const DB_NAME = 'offline-vue-db';
const DB_VERSION = 1;
export const dbPromise = openDB(DB_NAME, DB_VERSION, {
upgrade(db) {
// Store for our Tasks
if (!db.objectStoreNames.contains('tasks')) {
db.createObjectStore('tasks', { keyPath: 'id' });
}
// Store for queuing offline changes
if (!db.objectStoreNames.contains('syncQueue')) {
db.createObjectStore('syncQueue', { keyPath: 'id', autoIncrement: true });
}
},
});
// --- Data Access Methods ---
export async function getTasks() {
return (await dbPromise).getAll('tasks');
}
export async function addTask(task) {
const db = await dbPromise;
await db.put('tasks', task);
// Add "ADD" operation to queue
await addToSyncQueue({ type: 'ADD', payload: task });
}
export async function deleteTask(id) {
const db = await dbPromise;
await db.delete('tasks', id);
// Add "DELETE" operation to queue
await addToSyncQueue({ type: 'DELETE', payload: { id } });
}
// --- Sync Queue Methods ---
async function addToSyncQueue(operation) {
const db = await dbPromise;
await db.add('syncQueue', operation);
}
export async function getSyncQueue() {
return (await dbPromise).getAll('syncQueue');
}
export async function clearSyncQueueItem(id) {
return (await dbPromise).delete('syncQueue', id);
}
2. The Application Logic (src/App.vue)
This component handles the UI, the fake server logic, and the synchronization process.
<script setup>
import { ref, onMounted } from 'vue';
import { getTasks, addTask, deleteTask, getSyncQueue, clearSyncQueueItem } from './db';
// --- State ---
const tasks = ref([]);
const newTaskInput = ref('');
const isOnline = ref(navigator.onLine);
const isSyncing = ref(false);
// --- Mock Server API ---
// In a real app, these would be fetch() calls to your backend
const fakeApi = {
post: (data) => new Promise((resolve, reject) => {
setTimeout(() => {
Math.random() > 0.1 ? resolve(data) : reject(new Error('Server Error'));
}, 500);
}),
delete: (id) => new Promise((resolve) => setTimeout(resolve, 500))
};
// --- Core Logic ---
const loadLocalData = async () => {
tasks.value = await getTasks();
};
const handleAddTask = async () => {
if (!newTaskInput.value.trim()) return;
const task = {
id: crypto.randomUUID(), // Generate ID locally! Don't wait for server.
title: newTaskInput.value,
createdAt: Date.now(),
synced: false // Visual indicator
};
// 1. Update UI immediately (Optimistic Update)
tasks.value.push(task);
newTaskInput.value = '';
// 2. Save to IndexedDB + Add to Queue
await addTask(task);
// 3. Try to sync immediately if online
if (isOnline.value) {
processSyncQueue();
}
};
const handleDelete = async (id) => {
// 1. Update UI
tasks.value = tasks.value.filter(t => t.id !== id);
// 2. Update DB + Queue
await deleteTask(id);
// 3. Sync
if (isOnline.value) {
processSyncQueue();
}
};
// --- Synchronization Engine ---
const processSyncQueue = async () => {
if (isSyncing.value || !isOnline.value) return;
const queue = await getSyncQueue();
if (queue.length === 0) return;
isSyncing.value = true;
for (const op of queue) {
try {
if (op.type === 'ADD') {
await fakeApi.post(op.payload);
// If success, allow UI to know this item is safe (optional logic)
} else if (op.type === 'DELETE') {
await fakeApi.delete(op.payload.id);
}
// Remove from queue only on success
await clearSyncQueueItem(op.id);
console.log(`Synced operation: ${op.type}`);
} catch (error) {
console.error('Sync failed, will retry later', error);
break; // Stop syncing if one fails, preserve order
}
}
isSyncing.value = false;
// Refresh local data to ensure consistency
// (In a real app, you might update the 'synced' status locally here)
};
// --- Event Listeners ---
const updateOnlineStatus = () => {
isOnline.value = navigator.onLine;
if (isOnline.value) {
console.log('Back Online: Processing queue...');
processSyncQueue();
}
};
onMounted(async () => {
await loadLocalData();
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);
// Initial sync attempt in case we reload page
if (isOnline.value) processSyncQueue();
});
</script>
<template>
<div class="container">
<header :class="{ offline: !isOnline }">
<h1>Offline-First Tasks</h1>
<div class="status">
<span v-if="isOnline" class="badge online">● Online</span>
<span v-else class="badge offline">● Offline (Changes Queued)</span>
<span v-if="isSyncing" class="badge sync">⟳ Syncing...</span>
</div>
</header>
<div class="input-group">
<input
v-model="newTaskInput"
@keyup.enter="handleAddTask"
placeholder="Add a task..."
/>
<button @click="handleAddTask">Add</button>
</div>
<ul>
<li v-for="task in tasks" :key="task.id">
<span>{{ task.title }}</span>
<button class="delete-btn" @click="handleDelete(task.id)">×</button>
</li>
</ul>
<p v-if="tasks.length === 0" class="empty">No tasks found.</p>
<div class="instructions">
<p><strong>Test this:</strong></p>
<ol>
<li>Disconnect your internet (or set Network to "Offline" in DevTools).</li>
<li>Add some items. note they appear immediately.</li>
<li>Refresh the page (data persists via IndexedDB).</li>
<li>Go back Online. Check console to see the queue flushing.</li>
</ol>
</div>
</div>
</template>
<style scoped>
.container { max-width: 500px; margin: 2rem auto; font-family: sans-serif; }
header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem; }
header.offline h1 { color: #777; }
.status { display: flex; gap: 10px; font-size: 0.85rem; }
.badge { padding: 4px 8px; border-radius: 12px; font-weight: bold; }
.online { background: #d4edda; color: #155724; }
.offline { background: #f8d7da; color: #721c24; }
.sync { background: #cce5ff; color: #004085; }
.input-group { display: flex; gap: 10px; margin-bottom: 1rem; }
input { flex: 1; padding: 8px; }
ul { list-style: none; padding: 0; }
li {
background: #f4f4f4; margin-bottom: 5px; padding: 10px;
display: flex; justify-content: space-between; align-items: center;
border-radius: 4px;
}
.delete-btn { background: #ff4d4d; color: white; border: none; border-radius: 50%; width: 24px; height: 24px; cursor: pointer; }
.empty { text-align: center; color: #888; }
.instructions { margin-top: 30px; font-size: 0.9rem; color: #555; background: #eee; padding: 15px; border-radius: 5px;}
</style>
How it works
-
UUID Generation:
Notice crypto.randomUUID() in handleAddTask. In offline-first apps, you cannot rely on the server to generate IDs (because the server might not be reachable). You must generate IDs on the client so you can save them to IndexedDB immediately.
-
The Queue Pattern:
When you add or delete an item, we don't just tell the server. We add an entry to the syncQueue object store in IndexedDB.
- We store the
type ('ADD', 'DELETE') and the payload (the task data).
- Even if the browser closes or crashes, that queue persists on disk.
-
Process Queue:
The processSyncQueue function acts as a "pump":
- It reads the queue from IndexedDB.
- It loops through operations.
- If an API call succeeds, it removes that item from the queue.
- If it fails (e.g., internet drops halfway), it stops. The operation remains in the queue to be tried again later.
-
Connectivity Listeners:
We use window.addEventListener('online', ...) to automatically trigger the queue processing the moment the internet connection returns.
Testing the Offline Capability
- Open Chrome DevTools.
- Go to the Network tab.
- Switch the throttling dropdown from "No throttling" to "Offline".
- Add tasks in the app. They will appear on the list because they are saved to IndexedDB.
- Check the Application tab in DevTools -> IndexedDB -> offline-vue-db. You will see your tasks in
tasks and pending operations in syncQueue.
- Switch Network back to "No throttling". Look at the Console logs to see the sync happening.