Esta página ainda não está disponível em Português, por isso está a ler a versão em inglês.

Offline-first data: IndexedDB, sync and conflict handling

Caching pages is easy. Keeping data in sync is the real work.

Cache e offline Avançado 2 min de leitura Revisado em 27 de nov. de 2026

Caching HTML and files gets your app to open offline. Letting people read and change data offline needs a local database and a sync plan.

Where to store data

StorageGood forNotes
IndexedDBStructured data, thousands of records, blobsThe main choice. Asynchronous, transactional, available in workers.
Cache APIHTTP responsesGreat for files and pages, not for querying.
OPFS (Origin Private File System)Large files, SQLite databasesFast; works in all modern browsers.
localStorageTiny settingsSynchronous and blocks the main thread; not available in service workers.

IndexedDB's raw API is verbose, so most apps use a small wrapper:

  • idb: a tiny promise wrapper that keeps the IndexedDB model.
  • Dexie: a friendlier query API, live queries, and an optional sync service.
  • localForage: a localStorage-like API backed by IndexedDB.
import { openDB } from 'idb';
const db = await openDB('notes', 1, {
  upgrade(db) {
    const s = db.createObjectStore('notes', { keyPath: 'id' });
    s.createIndex('updated', 'updated');
    db.createObjectStore('outbox', { autoIncrement: true });
  },
});
await db.put('notes', { id: crypto.randomUUID(), text: 'Buy milk', updated: Date.now() });

Writing offline: the outbox pattern

  1. Save the change locally first, and update the UI at once.
  2. Add the change to an outbox store.
  3. When online, send outbox items to the server in order, and remove each one when the server confirms.
async function save(note) {
  await db.put('notes', note);
  await db.add('outbox', { op: 'put', note });
  flush();
}
async function flush() {
  if (!navigator.onLine) return;
  const tx = db.transaction('outbox', 'readwrite');
  for await (const cursor of tx.store) {
    const res = await fetch('/api/notes', { method: 'POST', body: JSON.stringify(cursor.value) }).catch(() => null);
    if (!res || !res.ok) break;
    await cursor.delete();
  }
}
addEventListener('online', flush);

In Chromium browsers, Background Sync can run flush from the service worker even after the tab is closed. Elsewhere, flush on online, on visibilitychange and on app start.

Conflicts

When the same record changes in two places, you need a rule:

  • Last write wins (by timestamp): simple, and fine for personal data.
  • Server wins, and the app shows the server version.
  • Field-level merge: merge different fields, flag real clashes.
  • CRDTs: data types that merge automatically. Yjs and Automerge power collaborative editors that work offline.

Full sync engines

If your app is mostly data, a sync-capable database saves months: RxDB (reactive, with replication plugins), PouchDB (syncs with CouchDB), Dexie Cloud, or SQLite in the browser via SQLite Wasm on OPFS.

Tell people what is happening

Show "Saved on this device" and "Synced" states, and a count of unsent changes. People trust offline apps when they can see what will happen to their data.

Compatibilidade de navegadores

Compatibilidade dos navegadores com recursos de PWA
RecursoChrome / Edge desktopChrome AndroidSafari iOS / iPadOSSafari macOSFirefox desktopFirefox AndroidSamsung Internet
IndexedDB Chrome / Edge desktop: Sim Chrome Android: Sim Safari iOS / iPadOS: Sim Safari macOS: Sim Firefox desktop: Sim Firefox Android: Sim Samsung Internet: Sim
Origin Private File System Chrome / Edge desktop: Sim Chrome Android: Sim Safari iOS / iPadOS: Sim Safari macOS: Sim Firefox desktop: Sim Firefox Android: Sim Samsung Internet: Sim
Background Sync Chrome / Edge desktop: Sim Chrome Android: Sim Safari iOS / iPadOS: Não Safari macOS: Não Firefox desktop: Não Firefox Android: Não Samsung Internet: Sim

Ver a tabela completa