What it means to save on the device first, and the one rule that keeps syncing sane.
An offline-first app saves what you type on your own device straight away and talks to the server later. The person using it never waits on a signal.
The basic loop
Every change goes into a small queue stored in the browser. A background step sends the queue when a connection is available and removes each item once the server confirms it.
const queue = JSON.parse(localStorage.getItem("queue") ?? "[]");
export function save(note) {
queue.push({ id: crypto.randomUUID(), note, at: Date.now() });
localStorage.setItem("queue", JSON.stringify(queue));
flush();
}
async function flush() {
while (queue.length && navigator.onLine) {
const item = queue[0];
const res = await fetch("/api/notes", { method: "POST", body: JSON.stringify(item) });
if (!res.ok) return;
queue.shift();
localStorage.setItem("queue", JSON.stringify(queue));
}
}One rule for conflicts
Two people editing the same note is where syncing gets hard. The rule I reach for is simple: one owner per note. Others can add comments, but only the owner can change the text. It removes most of the cases you would otherwise have to resolve by hand.
