Local-First Web Apps: IndexedDB, Sync Engines, and CRDTs for Offline-Ready UIs
A practical guide to building local-first web apps. Learn how local-first differs from offline caching, how to store data with IndexedDB, OPFS, and SQLite in WebAssembly, how to build an optimistic outbox, how last-write-wins and CRDTs like Yjs resolve conflicts, how sync engines compare, and how to handle migrations, multiple tabs, auth, and offline testing.
Table of Contents
- Introduction
- What Local-First Actually Means
- Local-First vs Offline-Capable vs Cache-First
- The Seven Ideals
- Choosing a Storage Layer
- IndexedDB with idb
- SQLite in WebAssembly on OPFS
- Storage Quotas and Persistence
- Reading Local Data in React
- Writes: Optimistic Updates and the Outbox
- Building an Outbox
- Flushing the Outbox
- Pulling Changes from the Server
- Resolving Conflicts
- Last-Write-Wins
- CRDTs
- A Shared List with Yjs
- Coordinating Multiple Tabs
- Sync Engines: Build vs Buy
- Running the Database Off the Main Thread
- Schema Migrations on the Client
- Auth and Authorization for Synced Data
- Testing Offline Behavior
- When Not to Go Local-First
- Common Pitfalls
- Best Practices
- Conclusion
Introduction
Most web apps treat the server as the only real copy of the data. Every click that changes something waits on a network round trip, every page load starts with a spinner, and a flaky connection turns the app into a stack of error toasts.
Local-first apps flip this around. The data lives in a database on the user’s device, the UI reads and writes that database directly, and a sync process moves changes to and from the server in the background. Interactions feel instant because they never wait on the network, and the app keeps working on a train, in a basement, or when your API is down.
Tools like Linear, Figma, and Excalidraw popularized this model, and the building blocks are now good enough for ordinary teams: IndexedDB is everywhere, SQLite runs in the browser through WebAssembly, CRDT libraries are mature, and several sync engines handle the hard parts for you.
This guide covers what local-first means, how to store data on the client, how to build an optimistic write queue, how conflicts get resolved, and what to watch out for in production. If you’re coming from server-state libraries, it helps to know how TanStack Query handles caching and optimistic updates, because local-first takes those ideas much further.
What Local-First Actually Means
Local-First vs Offline-Capable vs Cache-First
These terms get mixed up a lot. The difference is about where the source of truth lives for the UI.
| Model | UI reads from | Writes go to | Works offline? |
|---|---|---|---|
| Server-first | Network (maybe a short cache) | Network, UI waits | No |
| Cache-first | HTTP or query cache, then network | Network, maybe optimistic | Read-only, for cached data |
| Offline-capable | Cache plus a service worker | Network, queued when offline | Partially, often as a fallback |
| Local-first | Local database, always | Local database, synced in background | Yes, by design |
In a cache-first app, the cache is a performance optimization. You can delete it and the app still works, just slower. In a local-first app, the local database is the app’s data model. The server is a sync peer and a backup, not something the UI talks to directly.
// ❌ Server-first: every interaction waits on the networkasync function toggleTodo(id: string) { setLoading(true); await fetch(`/api/todos/${id}/toggle`, { method: "POST" }); await refetchTodos(); setLoading(false);}
// ✅ Local-first: write locally, the UI updates immediately, sync happens laterasync function toggleTodo(id: string) { await db.todos.update(id, (todo) => ({ ...todo, done: !todo.done })); // A background sync process pushes this change to the server}The Seven Ideals
The term comes from the 2019 Ink & Switch essay “Local-first software.” It lists seven ideals. You don’t need all of them to benefit, but they’re a useful checklist:
- No spinners: reads and writes hit local storage, so they’re fast
- Your work isn’t trapped on one device: data syncs across devices
- The network is optional: the app works offline
- Seamless collaboration: multiple users can edit the same data
- The Long Now: data stays usable even if the vendor goes away
- Security and privacy by default: data can be encrypted end-to-end
- You retain ownership and control: users can export and keep their data
Most production web apps aim for the first four. The last three matter more for tools like note-taking apps, where users care about owning their data.
Choosing a Storage Layer
Browsers give you several places to store data. Only a few are suitable for a local database.
| Storage | Capacity | API | Good for |
|---|---|---|---|
localStorage | ~5 MB | Sync, strings | Small preferences. Blocks the main thread |
| IndexedDB | Large (quota) | Async, objects | Structured records, indexes, works everywhere |
| OPFS | Large (quota) | Async + sync in workers | Files, and the backing store for SQLite |
| SQLite (WASM) on OPFS | Large (quota) | SQL | Relational data, joins, complex queries |
| Cache Storage | Large (quota) | Request/Response | HTTP responses for service workers |
localStorage is synchronous and string-only, so it doesn’t belong in this list for anything beyond a few keys. Cache Storage is for HTTP responses, which we cover in the HTTP caching guide. For app data, the real choice is IndexedDB or SQLite on OPFS.
IndexedDB with idb
IndexedDB is supported in every browser and stores structured-cloneable values with indexes and transactions. Its raw API is event-based and awkward, so most people use Jake Archibald’s small idb wrapper, which adds Promises and TypeScript types.
import { openDB, type DBSchema } from "idb";
interface Todo { id: string; title: string; done: boolean; listId: string; updatedAt: number;}
interface AppDB extends DBSchema { todos: { key: string; value: Todo; indexes: { "by-list": string }; };}
export const dbPromise = openDB<AppDB>("app", 1, { upgrade(db) { const todos = db.createObjectStore("todos", { keyPath: "id" }); todos.createIndex("by-list", "listId"); },});
export async function getTodosForList(listId: string) { const db = await dbPromise; return db.getAllFromIndex("todos", "by-list", listId);}
export async function putTodo(todo: Todo) { const db = await dbPromise; await db.put("todos", todo);}IndexedDB transactions auto-commit as soon as there’s no pending request, so don’t await unrelated work (like fetch) inside a transaction. The transaction will close and the next operation throws TransactionInactiveError.
// ❌ The transaction commits while fetch is pendingconst tx = db.transaction("todos", "readwrite");const todo = await tx.store.get(id);const remote = await fetch(`/api/todos/${id}`); // tx is now inactiveawait tx.store.put({ ...todo, ...(await remote.json()) }); // throws
// ✅ Do network work first, then a short transactionconst remote = await (await fetch(`/api/todos/${id}`)).json();const tx = db.transaction("todos", "readwrite");const todo = await tx.store.get(id);await tx.store.put({ ...todo, ...remote });await tx.done;IndexedDB works well for key-value access and simple index lookups. It gets painful when you need joins, aggregates, or full-text search, because you end up writing a query engine by hand.
SQLite in WebAssembly on OPFS
The Origin Private File System (OPFS) is a private, sandboxed file system for each origin. Inside a worker, it offers synchronous file handles (createSyncAccessHandle()) that are fast enough to back a real database. That made it possible to run SQLite in the browser with durable storage.
The official build is published as @sqlite.org/sqlite-wasm. It must run in a worker to use OPFS:
import sqlite3InitModule from "@sqlite.org/sqlite-wasm";
const sqlite3 = await sqlite3InitModule();
// "opfs-sahpool" doesn't require cross-origin isolation headersconst pool = await sqlite3.installOpfsSAHPoolVfs({ name: "app-pool" });const db = new pool.OpfsSAHPoolDb("/app.sqlite3");
db.exec(` CREATE TABLE IF NOT EXISTS todos ( id TEXT PRIMARY KEY, list_id TEXT NOT NULL, title TEXT NOT NULL, done INTEGER NOT NULL DEFAULT 0, updated_at INTEGER NOT NULL ); CREATE INDEX IF NOT EXISTS todos_by_list ON todos(list_id);`);
export function todosForList(listId: string) { return db.selectObjects( "SELECT * FROM todos WHERE list_id = ? ORDER BY updated_at DESC", [listId], );}SQLite’s WASM build ships more than one OPFS-backed VFS. The plain opfs VFS uses SharedArrayBuffer and needs cross-origin isolation headers. The opfs-sahpool VFS avoids that requirement and is usually faster, at the cost of not supporting multiple connections to the same database at once. Community wrappers such as wa-sqlite offer other trade-offs. Check the current docs, since this area moves quickly.
Here’s how the two options compare:
| Concern | IndexedDB | SQLite on OPFS |
|---|---|---|
| Bundle size | ~1 KB with idb | Roughly 1 MB of WASM |
| Queries | Key and index lookups | Full SQL, joins, aggregates, FTS |
| Runs on main thread | Yes | No, needs a worker for OPFS |
| Browser support | Universal | Modern browsers |
| Matches server schema | You design a separate shape | Can mirror a Postgres schema closely |
Start with IndexedDB if your data is mostly lists of records. Move to SQLite when you find yourself building indexes and filtering logic by hand.
Storage Quotas and Persistence
Browser storage isn’t unlimited, and by default it’s best-effort: the browser may evict it under storage pressure. Two APIs help:
// How much space are we using, and how much do we have?const { usage, quota } = await navigator.storage.estimate();console.log( `Using ${(usage! / 1e6).toFixed(1)} MB of ${(quota! / 1e6).toFixed(0)} MB`,);
// Ask the browser not to evict our dataif (navigator.storage.persist) { const persisted = await navigator.storage.persisted(); if (!persisted) { const granted = await navigator.storage.persist(); console.log(granted ? "Storage is persistent" : "Storage may be evicted"); }}Chromium grants persistence based on engagement signals, such as whether the site is installed or bookmarked. Firefox may show a prompt. Safari has its own rules, and its tracking prevention can clear script-written storage for sites the user hasn’t interacted with in a while, unless the site is installed to the home screen.
The practical takeaway is that local data can disappear. The server copy must always be enough to rebuild the local database, and any unsynced writes are at risk until they reach the server.
Reading Local Data in React
A local database is an external store, so React’s useSyncExternalStore is the right integration point. The pattern is to keep an in-memory snapshot, update it whenever the database changes, and notify subscribers.
type Listener = () => void;
let snapshot: Todo[] = [];const listeners = new Set<Listener>();
export async function refresh(listId: string) { snapshot = await getTodosForList(listId); listeners.forEach((listener) => listener());}
export function subscribe(listener: Listener) { listeners.add(listener); return () => listeners.delete(listener);}
export function getSnapshot() { return snapshot;}import { useEffect, useSyncExternalStore } from "react";import { getSnapshot, refresh, subscribe } from "./todoStore";
export function TodoList({ listId }: { listId: string }) { const todos = useSyncExternalStore(subscribe, getSnapshot);
useEffect(() => { refresh(listId); }, [listId]);
return ( <ul> {todos.map((todo) => ( <li key={todo.id}>{todo.title}</li> ))} </ul> );}getSnapshot must return the same reference until the data actually changes, or React re-renders forever. That’s why the store replaces snapshot only inside refresh.
Most sync engines and libraries give you this as a ready-made hook (often called useQuery or useLiveQuery) that re-runs a query whenever the underlying tables change. If you build your own, keep the external store pattern. It fits the store-based approach covered in our state management guide.
Writes: Optimistic Updates and the Outbox
In a server-first app, optimistic updates are a trick: you update the cache, send the request, and roll back on failure. In a local-first app, every write is local first by design. The question is how to reliably get those writes to the server.
The standard answer is an outbox: a durable queue of pending mutations stored in the same database as the data.
Building an Outbox
Each mutation gets a unique ID that doubles as an idempotency key, so the server can safely ignore duplicates when a request is retried.
interface Mutation { id: string; // idempotency key name: "createTodo" | "toggleTodo" | "deleteTodo"; args: unknown; createdAt: number;}
interface AppDB extends DBSchema { todos: { key: string; value: Todo; indexes: { "by-list": string } }; outbox: { key: string; value: Mutation; indexes: { "by-created": number } }; meta: { key: string; value: { key: string; value: number } };}
export async function toggleTodo(id: string) { const db = await dbPromise; const tx = db.transaction(["todos", "outbox"], "readwrite");
const todo = await tx.objectStore("todos").get(id); if (!todo) return;
// Apply the change locally and record the mutation in the same transaction await tx .objectStore("todos") .put({ ...todo, done: !todo.done, updatedAt: Date.now() }); await tx.objectStore("outbox").put({ id: crypto.randomUUID(), name: "toggleTodo", args: { id }, createdAt: Date.now(), });
await tx.done; scheduleFlush();}Writing the data change and the outbox entry in one transaction matters. If the tab crashes between the two, you’d otherwise end up with a local change the server never hears about, or a queued mutation for a change that never happened.
Notice that the outbox stores the intent (toggleTodo with an ID) rather than the resulting row. Sending intents lets the server re-run the mutation against its own current state, which is how many sync engines handle conflicts. Replicache and Zero call these custom mutators: the same mutation code runs optimistically on the client and authoritatively on the server.
Flushing the Outbox
The flush loop sends pending mutations in order, removes the ones the server accepted, and backs off on failure.
let flushing = false;let retryDelay = 1_000;
export function scheduleFlush() { if (!flushing) void flush();}
async function flush() { flushing = true; try { const db = await dbPromise;
while (true) { const pending = await db.getAllFromIndex( "outbox", "by-created", undefined, 50, ); if (pending.length === 0) break;
const response = await fetch("/api/push", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ mutations: pending }), });
if (!response.ok) throw new Error(`Push failed: ${response.status}`);
const { applied } = (await response.json()) as { applied: string[] }; const tx = db.transaction("outbox", "readwrite"); await Promise.all(applied.map((id) => tx.store.delete(id))); await tx.done; }
retryDelay = 1_000; } catch { // Offline or server error: retry later with exponential backoff setTimeout(scheduleFlush, retryDelay); retryDelay = Math.min(retryDelay * 2, 60_000); } finally { flushing = false; }}
window.addEventListener("online", scheduleFlush);A few details are easy to get wrong:
- Order matters. Send mutations in creation order and have the server apply them in order. “Create todo” must land before “toggle todo”
- Don’t trust
navigator.onLine. It only tells you whether there’s a network interface, not whether your server is reachable. Use it as a hint to retry sooner, never as a reason to skip a request - Rejected mutations need a policy. If the server rejects a mutation for validation or permission reasons, retrying forever won’t help. Remove it, roll back the local change (usually by re-pulling the server state), and tell the user
- Background Sync (
registration.sync.register()) lets a service worker flush after the tab closes, but it’s Chromium-only. Treat it as a bonus
Pulling Changes from the Server
Pushing is half of sync. The client also needs changes made by other devices and users. The common approach is a cursor: the client stores the last version it has seen and asks for everything after it.
async function pull() { const db = await dbPromise; const cursor = (await db.get("meta", "cursor"))?.value ?? 0;
const response = await fetch(`/api/pull?since=${cursor}`); const { changes, nextCursor } = (await response.json()) as { changes: Array<{ op: "put"; todo: Todo } | { op: "delete"; id: string }>; nextCursor: number; };
const tx = db.transaction(["todos", "meta"], "readwrite"); for (const change of changes) { if (change.op === "put") await tx.objectStore("todos").put(change.todo); else await tx.objectStore("todos").delete(change.id); } await tx.objectStore("meta").put({ key: "cursor", value: nextCursor }); await tx.done;}On the server, the cursor is usually a monotonically increasing version number stored on each row (or a row in a change log). Deletes need to be recorded as tombstones so clients can learn about them. If you just delete the row, there’s nothing to send.
When to pull is a separate decision. A WebSocket or Server-Sent Events connection can send a “something changed” signal, and the client pulls in response. That’s often simpler than streaming the data itself over the socket. See our real-time communication guide for the trade-offs between transports.
There’s one more subtlety. When a pull arrives while local mutations are still in the outbox, the server state doesn’t include them yet. Naively applying the pull would make the user’s pending changes flicker away. Sync engines solve this with rebasing: apply the server state, then re-run pending local mutations on top. That’s one of the main reasons to use an engine instead of building your own.
Resolving Conflicts
Conflicts happen when two replicas change the same data before seeing each other’s changes. Two users edit the same title, or one device deletes a todo while another renames it. The question is what the merged result should be.
Last-Write-Wins
The simplest strategy is last-write-wins (LWW): each value carries a timestamp, and the newest one wins. Doing it per field rather than per row keeps unrelated edits from overwriting each other.
interface LWWField<T> { value: T; timestamp: number; clientId: string; // tiebreaker for equal timestamps}
function mergeField<T>(local: LWWField<T>, remote: LWWField<T>): LWWField<T> { if (remote.timestamp > local.timestamp) return remote; if (remote.timestamp < local.timestamp) return local; return remote.clientId > local.clientId ? remote : local;}
// User A renames the todo, User B marks it done at the same time.// Per-field LWW keeps both changes. Per-row LWW would lose one.The weak point is the timestamp. Device clocks drift and can be wrong by minutes, so a device with a fast clock “wins” every conflict. Production systems use hybrid logical clocks (HLCs), which combine wall-clock time with a counter so that timestamps always move forward and respect causality. An even simpler option is to let the server assign the order: it applies mutations in the order it receives them, which is exactly what the intent-based outbox above does.
LWW is good enough for most app data: titles, statuses, settings, and form fields. It falls apart for collaborative text, where “keep the last version” means throwing away someone’s paragraph.
CRDTs
Conflict-free replicated data types (CRDTs) are data structures designed so that replicas can apply changes in any order and still converge to the same state, with no central server deciding. Instead of storing “the title is X,” a text CRDT stores each inserted character with a unique ID and position relative to its neighbors. Concurrent inserts are both kept, and every replica orders them the same way.
| Type | Example use | Merge behavior |
|---|---|---|
| LWW register | A todo’s title | Highest timestamp wins |
| Grow-only counter | Like count | Sum of each replica’s increments |
| Observed-remove set | Tags on a document | Concurrent add and remove: add wins |
| Sequence / text | Collaborative document | Concurrent inserts are both kept, ordered by ID |
| Map | Nested JSON document | Per-key merge using one of the above |
You almost never implement these yourself. The two mature JavaScript libraries are Yjs and Automerge. Yjs is known for performance and a large ecosystem of editor bindings (ProseMirror, Tiptap, CodeMirror, Monaco). Automerge models a JSON document with full history and has a Rust core compiled to WASM.
A Shared List with Yjs
Here’s a minimal shared todo list with Yjs. Each Y.Doc is a replica, and updates are small binary blobs you can send over any transport.
import * as Y from "yjs";
const doc = new Y.Doc();const todos = doc.getArray<Y.Map<unknown>>("todos");
export function addTodo(title: string) { const todo = new Y.Map<unknown>(); todo.set("id", crypto.randomUUID()); todo.set("title", title); todo.set("done", false); todos.push([todo]);}
export function toggleTodo(index: number) { const todo = todos.get(index); todo.set("done", !todo.get("done"));}
// React to any change, local or remotetodos.observeDeep(() => { render(todos.toJSON());});
// Send local changes to peers or a serverdoc.on("update", (update: Uint8Array, origin: unknown) => { if (origin !== "remote") socket.send(update);});
// Apply changes from peerssocket.addEventListener("message", async (event) => { const update = new Uint8Array(await (event.data as Blob).arrayBuffer()); Y.applyUpdate(doc, update, "remote");});To see convergence, simulate two replicas making concurrent changes:
const a = new Y.Doc();const b = new Y.Doc();
a.getText("title").insert(0, "Groceries");Y.applyUpdate(b, Y.encodeStateAsUpdate(a));
// Both edit at the same time, without seeing each other's changea.getText("title").insert(9, " for Monday");b.getText("title").insert(0, "Weekly ");
// Exchange updates in either orderY.applyUpdate(a, Y.encodeStateAsUpdate(b));Y.applyUpdate(b, Y.encodeStateAsUpdate(a));
console.log(a.getText("title").toString()); // "Weekly Groceries for Monday"console.log(b.getText("title").toString()); // "Weekly Groceries for Monday"In a real app you wouldn’t wire the socket by hand. Yjs has providers: y-indexeddb persists the document locally, and y-websocket (or a hosted service) syncs it with a server. Combining the two gives you an offline-capable collaborative document in a few lines.
CRDTs have costs. Documents keep metadata about past operations, so they grow over time. Yjs garbage-collects deleted content by default, but history-heavy documents can still get large. And CRDTs only guarantee that replicas converge, not that the result makes sense for your app. If two users concurrently move the last item out of a list that must never be empty, both moves succeed. Business rules still need a server.
A common pattern is to mix the two approaches: use a CRDT for rich-text fields and collaborative canvases, and server-ordered LWW for everything else.
Coordinating Multiple Tabs
Users open your app in several tabs. Each tab shares the same IndexedDB or OPFS storage, which raises two problems: tabs must learn about each other’s writes, and only one of them should run the sync loop.
BroadcastChannel lets tabs on the same origin notify each other:
const channel = new BroadcastChannel("db-changes");
export async function afterLocalWrite(listId: string) { await refresh(listId); channel.postMessage({ type: "changed", listId });}
channel.addEventListener("message", (event) => { if (event.data.type === "changed") refresh(event.data.listId);});The Web Locks API elects a single leader. The callback holds the lock for as long as its Promise is pending, and when the leader tab closes, the lock passes to the next waiting tab automatically:
navigator.locks.request("sync-leader", async () => { // Only one tab gets here at a time startSyncLoop(); await new Promise(() => {}); // hold the lock until this tab closes});The leader runs the WebSocket connection, flushes the outbox, and pulls changes. Other tabs write locally and broadcast. This also matters for the opfs-sahpool SQLite VFS, which allows only one connection at a time. Some setups go further and run the database in a SharedWorker that every tab talks to.
Sync Engines: Build vs Buy
Everything above (outbox, cursors, rebasing, tombstones, leader election, partial sync, permissions) is a lot to build and maintain. Sync engines package it up. They differ mostly in what database they sync with, how writes flow, and how much of your backend they take over.
| Engine | Server data source | Client store | How writes work |
|---|---|---|---|
| Zero (Rocicorp) | Postgres | Local cache with queries | Custom mutators run on client and server |
| Replicache (Rocicorp) | Your backend | IndexedDB | Push/pull protocol you implement on the server |
| Electric | Postgres | Your choice | Read-path sync of “shapes”; writes through your API |
| PowerSync | Postgres, MongoDB, MySQL | SQLite | Upload queue that calls your backend |
| Yjs / Automerge + provider | Any store for blobs | IndexedDB | CRDT updates, merged automatically |
The table describes each project’s general approach. Check their current docs before you choose, because features and status change quickly in this space.
A few questions narrow the choice:
- Do you already have a Postgres database you want to keep as the source of truth? Engines that replicate from Postgres (Zero, Electric, PowerSync) slot in next to your existing backend
- Do writes need server-side validation and business rules? Prefer engines where writes go through your own code (custom mutators, an upload queue, or your API)
- Is the core of your app a collaborative document or canvas? A CRDT library with a provider fits better than a row-based engine
- How much data does each user need? Every engine has some notion of partial sync: shapes, queries, or sync rules that define which subset of rows each client receives. Syncing the whole database to every client only works for tiny datasets
Building your own is reasonable when your data model is simple (a single user’s records, with no collaboration) and LWW conflicts are acceptable. In that case, an outbox, a cursor-based pull, and a BroadcastChannel cover most of what you need.
Running the Database Off the Main Thread
Local queries are fast, but they still take time. Hydrating thousands of rows, running a SQL join, or applying a large pull can create long tasks that hurt Interaction to Next Paint. SQLite on OPFS already requires a worker. With IndexedDB, it’s worth moving heavy processing into one too.
Comlink makes a worker-hosted database feel like a normal async API:
import * as Comlink from "comlink";
const api = { todosForList(listId: string) { return db.selectObjects("SELECT * FROM todos WHERE list_id = ?", [listId]); }, toggleTodo(id: string) { db.exec("UPDATE todos SET done = NOT done, updated_at = ? WHERE id = ?", { bind: [Date.now(), id], }); },};
export type DbApi = typeof api;Comlink.expose(api);import * as Comlink from "comlink";import type { DbApi } from "./db.worker";
const worker = new Worker(new URL("./db.worker.ts", import.meta.url), { type: "module",});export const db = Comlink.wrap<DbApi>(worker);
const todos = await db.todosForList("inbox");Running the sync loop in the same worker keeps network parsing and merges off the main thread as well. The main thread only sends queries and receives small result sets.
Schema Migrations on the Client
On the server, you run a migration once. On the client, every device runs its own migration whenever it loads a new version of your app, possibly after months offline, possibly while holding unsynced writes.
With IndexedDB, migrations live in the upgrade callback and run when you bump the version number:
export const dbPromise = openDB<AppDB>("app", 3, { async upgrade(db, oldVersion, _newVersion, tx) { if (oldVersion < 1) { const todos = db.createObjectStore("todos", { keyPath: "id" }); todos.createIndex("by-list", "listId"); } if (oldVersion < 2) { db.createObjectStore("outbox", { keyPath: "id" }).createIndex( "by-created", "createdAt", ); db.createObjectStore("meta", { keyPath: "key" }); } if (oldVersion < 3) { // Backfill a new field on existing records let cursor = await tx.objectStore("todos").openCursor(); while (cursor) { await cursor.update({ ...cursor.value, priority: cursor.value.priority ?? "normal", }); cursor = await cursor.continue(); } } }, blocked() { // Another tab has the old version open alert("Please close other tabs of this app to finish updating."); },});Write migrations as a chain of if (oldVersion < n) steps so a device can jump from any old version to the newest one.
The harder problem is the sync protocol between old clients and a new server. A client that has been offline for weeks may push mutations in an old format. Some practical rules:
- Version your mutations and pull responses. Include a schema version in every push, and keep the server able to accept the previous one or two versions
- Make changes additive. Add new fields and tables instead of renaming or removing them. Remove old ones only after clients have had time to update
- Have an escape hatch. If a client is too old, the server should tell it to flush what it can, wipe local data, and resync from scratch
- Never drop the outbox in a migration. Those are writes the user believes are saved
Auth and Authorization for Synced Data
Once data lives on the client, two security assumptions change.
First, everything synced to the device is readable by the user. Anyone can open DevTools and inspect IndexedDB. The server must filter data before it’s sent, based on who the user is. A client-side WHERE user_id = ? is a convenience, not a permission check. This is why partial sync rules in sync engines are written on the server.
Second, every pushed mutation must be authorized on the server, just like a normal API request. The client’s optimistic write proves nothing. Re-check permissions on every mutation, using the same session or token handling you’d use for any other endpoint. See our authentication and authorization guide for those patterns.
Local-first adds a few specific cases:
- Logout must clear local data. Delete the IndexedDB database or OPFS files, and clear the outbox (or flush it first). Otherwise, the next person on a shared computer sees the previous user’s data
- Permissions change while clients are offline. When a user loses access to a project, the server must send a “remove these rows” signal on the next pull, not just stop sending updates
- Expired sessions shouldn’t lose writes. If a push fails with 401, keep the outbox, send the user through sign-in, and resume flushing afterward
- Sensitive data might not belong on the device at all. Keep it server-only, or encrypt it at rest with a key that’s cleared on logout
Testing Offline Behavior
Local-first apps have more states than server-first apps: offline, online with pending writes, mid-sync, and conflicted. You need tests that exercise those transitions.
Playwright can take a browser context offline, which makes the important flows straightforward to test end to end:
import { test, expect } from "@playwright/test";
test("edits made offline sync when the connection returns", async ({ page, context,}) => { await page.goto("/lists/inbox"); await expect(page.getByRole("listitem")).toHaveCount(3);
await context.setOffline(true);
await page.getByRole("textbox", { name: "New todo" }).fill("Buy milk"); await page.keyboard.press("Enter");
// The UI updates immediately while offline await expect(page.getByText("Buy milk")).toBeVisible(); await expect(page.getByText("1 change pending")).toBeVisible();
// The change survives a reload while still offline await page.reload(); await expect(page.getByText("Buy milk")).toBeVisible();
await context.setOffline(false); await expect(page.getByText("All changes saved")).toBeVisible();
// A second client sees the change const other = await context.browser()!.newPage(); await other.goto("/lists/inbox"); await expect(other.getByText("Buy milk")).toBeVisible();});Reloading while offline only works if a service worker serves the app shell, so this test checks that too. For more on structuring end-to-end suites, see our Playwright vs Cypress comparison.
Unit tests should cover the logic that’s easy to get subtly wrong:
- Merge functions: Given two concurrent changes, does every replica end up in the same state regardless of the order they’re applied?
- The outbox: Are mutations sent in order? Are duplicates harmless? Are rejected mutations removed?
- Migrations: Open a database created by each old version and verify it upgrades correctly.
fake-indexeddblets you run these in Node
Property-based testing works especially well for merge logic. Generate random sequences of operations, apply them in different orders on different replicas, and assert that every replica converges.
When Not to Go Local-First
Local-first is a trade-off, not an upgrade. It moves complexity from “waiting on the network” to “keeping replicas consistent,” and that isn’t always worth it.
Avoid it, or keep it to small parts of the app, when:
- The operation needs strong consistency. Payments, inventory, seat booking, and anything where two people must not both succeed. These need a server to say yes or no before you show success
- The data is huge or mostly public. Search results, product catalogs, and social feeds are better served by queries and caching than by syncing millions of rows
- The data is short-lived. A dashboard of live metrics doesn’t benefit from being stored locally
- Your app is mostly forms that submit to a workflow. If every action triggers server-side side effects, an optimistic local write doesn’t buy much
- Your team can’t take on the operational cost. Client migrations, sync debugging, and storage eviction are new kinds of bugs
Many apps do best with a hybrid: a local-first core for the data users actively edit (documents, tasks, notes, settings) and ordinary server requests for everything else.
Common Pitfalls
Pitfall 1: Treating the Local Database as a Cache
If your code assumes the server will fix any inconsistency on the next fetch, you’ll lose writes. In local-first apps, unsynced changes exist only on the device. Store them durably, in the same transaction as the data change.
Pitfall 2: Trusting navigator.onLine
navigator.onLine reports true on captive portals, behind broken VPNs, and when your API is down. Always attempt the request and handle failure. Use the online event only to retry sooner.
Pitfall 3: Using Device Clocks to Order Changes
Client clocks drift, and users change them. A device with a wrong clock can win or lose every conflict. Use server-assigned order or hybrid logical clocks.
Pitfall 4: Deleting Rows Without Tombstones
If the server simply deletes a row, clients pulling “changes since version N” never learn that it’s gone. Record deletions as tombstones, and expire them only after every client has had time to sync.
Pitfall 5: Syncing Everything to Every Client
Sending the whole dataset works in a demo and fails with real customers. Define partial sync rules early, based on what each user is allowed to see and actually needs.
Pitfall 6: Forgetting Other Tabs
Two tabs running their own sync loops send duplicate requests and race each other. A tab that doesn’t hear about another tab’s writes shows stale data. Use Web Locks for leadership and BroadcastChannel for change notifications.
Pitfall 7: Assuming Storage Lasts Forever
Browsers can evict best-effort storage, and Safari may clear it for sites users haven’t visited recently. Request persistent storage, flush writes promptly, and make sure a full resync from the server always works.
Best Practices
✅ Practice 1: Make the Server the Durable Copy
The local database makes the app fast and offline-capable. The server makes the data durable and shareable. Design so that any device can be wiped and rebuilt from the server.
✅ Practice 2: Send Intents, Not Final State
Queue mutations like toggleTodo(id) instead of full rows. The server can re-run them against current data, enforce business rules, and resolve many conflicts automatically.
✅ Practice 3: Make Every Mutation Idempotent
Give each mutation a unique ID and have the server ignore IDs it has already applied. Retries then become safe, which is essential on unreliable networks.
✅ Practice 4: Pick the Simplest Conflict Strategy That Works
Per-field LWW with server ordering covers most app data. Reach for CRDTs for collaborative text and canvases, where losing a concurrent edit isn’t acceptable.
✅ Practice 5: Show Sync Status
Tell users when changes are pending, when they’re saved, and when something failed. A small “Saving…” or “Offline: 3 changes pending” indicator builds trust that local-first writes aren’t lost.
✅ Practice 6: Keep Heavy Work in a Worker
Run the database, the sync loop, and large merges in a worker. The main thread should only render and send small queries.
✅ Practice 7: Plan Migrations and Protocol Versions From Day One
Version your local schema and your sync protocol, keep changes additive, and build the “wipe and resync” escape hatch before you need it.
Conclusion
Local-first apps feel different from traditional web apps. There are no spinners on every click, no lost work when the connection drops, and collaboration arrives in real time. That experience comes from one architectural decision: the UI talks to a database on the device, and syncing with the server is a background concern.
Key Takeaways:
- Local-first means the local database is the UI’s source of truth and the server is a sync peer, unlike cache-first apps where the cache is just an optimization
- IndexedDB with
idbworks everywhere and suits record-based data. SQLite on OPFS in a worker adds full SQL at the cost of a larger bundle - Storage is best-effort by default. Request persistence with
navigator.storage.persist()and always keep the server copy complete - An outbox of idempotent, intent-based mutations, written in the same transaction as the data change, makes optimistic writes reliable
- Pulls use cursors and tombstones, and sync engines rebase pending local writes on top of incoming server state
- Last-write-wins per field, ordered by the server or a hybrid logical clock, handles most conflicts. CRDTs like Yjs and Automerge handle collaborative text
- Web Locks and
BroadcastChannelcoordinate multiple tabs - Sync engines like Zero, Electric, and PowerSync handle partial sync, rebasing, and permissions so you don’t have to
- Security still lives on the server: filter what syncs to each client, authorize every mutation, and clear local data on logout
- Not everything should be local-first. Payments, inventory, and huge public datasets need the server in the loop
A good way to start is to pick one feature that users edit often, such as a task list, notes, or settings. Make it read and write from IndexedDB with an outbox, add a “pending changes” indicator, and test it with Playwright in offline mode. Once that feels solid, you’ll know whether to expand the approach or adopt a sync engine.
For more on related topics, check out our guides on HTTP caching and service workers, Web Workers, and TanStack Query.