Offline-first sync with PouchDB, and what to do about conflicts
Most 'offline support' is a cache: show the last data you saw, and refuse to save until the network is back. Offline-first is different.
Most “offline support” is a cache: show the last data you saw, and refuse to save until the network is back. Offline-first is different. The app writes to a local database, always, and syncing with the server happens in the background whenever it can.
PouchDB is still one of the simplest ways to get there. It’s a JavaScript database that runs in the browser on top of IndexedDB, and it speaks CouchDB’s replication protocol. Point it at a CouchDB server and the two keep each other in sync, in both directions, through any number of disconnects.
The syncing is the easy part. Conflicts are where you have to think.
The whole sync setup
import PouchDB from 'pouchdb-browser';
const local = new PouchDB('notes');
const remote = new PouchDB('https://couch.example.com/notes');
local
.sync(remote, { live: true, retry: true })
.on('change', (info) => console.log(info.direction, info.change.docs.length))
.on('paused', () => setStatus('up to date (or offline)'))
.on('active', () => setStatus('syncing'))
.on('error', (err) => setStatus(`sync stopped: ${err.message}`));
That’s it. live keeps it running, retry keeps reconnecting after network drops. Your UI reads and writes local only, and never waits for the network.
Every change needs the current revision
Every document has an _id and a _rev. To update a document, you must send the _rev you’re updating. Send an old one and you get a 409:
const note = await local.get('note:1');
await local.put({ ...note, text: 'buy milk and eggs' }); // ok
await local.put({ ...note, text: 'something else' }); // 409 conflict: stale _rev
This is optimistic locking, and it only protects you within one database. A 409 means “someone changed this since you read it”: read it again, re-apply your change, and try once more.
Conflicts from replication are silent
Now the real case. A note is synced to two devices. Both go offline. On the phone, you change the text. On the laptop, you add a tag. Both writes succeed locally, because each device had the current _rev as far as it knew.
When they sync, there’s no error. Both devices end up showing the same version: CouchDB’s rules pick a winner deterministically (the longer edit history wins, and ties are broken by comparing revision IDs), so every copy agrees without talking to each other. The other version isn’t deleted. It’s kept as a conflicting revision, and nothing shows it unless you ask:
const note = await local.get('note:1', { conflicts: true });
// note.text -> 'buy milk' (laptop's version won)
// note.tags -> ['shopping']
// note._conflicts -> ['2-733e67b0...'] (the phone's edit is in here)
That’s what I got when I reproduced this with two in-memory databases. From the user’s point of view, the text they typed on the phone just vanished. It’s still in the database, but the app has to go and get it.
Resolving a conflict
Resolution is up to you, because only you know what “merged” means for your data. The mechanics are always the same: read the winner and the losers, write a merged version on top of the winner, and delete the losing revisions so the conflict is gone.
async function resolve(db, id, merge) {
const winner = await db.get(id, { conflicts: true });
if (!winner._conflicts) return winner;
const losers = await Promise.all(
winner._conflicts.map((rev) => db.get(id, { rev })),
);
const { _conflicts, ...merged } = losers.reduce(merge, winner);
await db.bulkDocs([
merged, // written on top of the winner's _rev
...losers.map((l) => ({ _id: l._id, _rev: l._rev, _deleted: true })),
]);
return db.get(id);
}
// keep the longer text, combine the tags
const mergeNotes = (a, b) => ({
...a,
text: a.text.length >= b.text.length ? a.text : b.text,
tags: [...new Set([...a.tags, ...b.tags])],
});
Run it from the change handler for documents that arrive with conflicts, or when the user opens a document. Once the resolution syncs, every device sees the merged version and no conflict.
Design so conflicts rarely happen
The best conflict is one that can’t happen. A few habits help a lot:
- One document per thing that changes independently. A shopping list stored as one document conflicts whenever two people tick items. One document per item almost never does.
- IDs that sort usefully. note:2024-09-12T10:31:00Z:abc lets you fetch a range with allDocs and never needs an index.
- Append rather than edit where you can. A comment thread as separate documents can’t conflict at all.
A change in 9.0 worth knowing
PouchDB 9.0, released in May, changed find() to return at most 25 documents unless you pass a limit. I checked with 40 matching documents: find() returned 25, with no warning. If a list in your app suddenly stops at 25 after upgrading, that’s why:
const { docs } = await local.find({
selector: { type: 'note' },
limit: 1000,
});
// or, with prefixed IDs, skip the index entirely:
const { rows } = await local.allDocs({
startkey: 'note:',
endkey: 'note:',
include_docs: true,
});
Where it fits
PouchDB is a great fit when the data belongs to a user or a small group, works fine as JSON documents, and needs to be editable offline: notes, field forms, checklists, inspections. It’s a poor fit when you need joins, strict server-side validation of every write, or many users editing the same records constantly. And it needs CouchDB (or a compatible server) on the other end, with its own authentication and per-user access to set up.
For the right app, though, it removes a whole category of code. There’s no sync queue to write, no retry logic, and no “you’re offline” error message. Just conflicts, which you now know how to find.