Engineering 41 min read

Building Offline-First with Dexie.js

MMNMNOTE
dexieindexeddboffline-firstlocal-firstpwareacttypescriptserwistyjscrdt
Updated September 23, 2026

Offline-first is the discipline of treating the network as an enhancement, not a dependency. IndexedDB is the only browser storage with the shape — async, transactional, indexed, blob-capable — to host a real local database. Dexie.js is the wrapper that makes that database usable. This post is the working stack.

The W3C Indexed Database API 3.0 is an Editor's Draft dated 13 August 2025 1. Dexie.js — "A Minimalistic Wrapper for IndexedDB" 2 — sits at v4.4.2 as of 31 March 2026 3. The Ink & Switch local-first essay (Onward! 2019) frames the seven ideals every offline-first app is measured against, beginning with "No spinners: your work at your fingertips" 4. Most production offline-first apps in 2026 are some configuration of those four nouns — IndexedDB, a wrapper, a sync layer, a service worker. The architecture is small. The traps are many.

Why offline-first matters

Offline-first matters because the network is not a property of your software — it is a property of the user's day. Trains, basements, airports, and roaming caps all produce the same state: the request hangs. Apps that treat that as exceptional become unusable five hours a week. Apps that treat it as default keep working.

The Ink & Switch paper, written by Martin Kleppmann and three collaborators, names this stance explicitly: "The network is optional" 4. The same paper opens the canonical seven ideals with a sharper claim — "No spinners: your work at your fingertips" — and closes with "You retain ultimate ownership and control" 4. Local-first is a stronger statement than offline-first; offline-first is the storage decision local-first requires. You cannot retain ownership of data you do not store. You cannot avoid spinners on writes you have to round-trip. The two stances are nested, and the work is the same.

The trade-off worth naming early: sync is harder than storage. A note app that stores locally and never syncs is straightforward. A note app that syncs across two browsers without conflict is a research problem with a name (CRDT) and a small library ecosystem 5 6 7. Build the local layer first. Decide on sync later — when the use case demands it, not when the announcement does.

Why IndexedDB, not localStorage or OPFS

IndexedDB is the only browser storage with the API shape an application database needs — asynchronous, transactional, indexed, structured-clone — and the only one with quotas in gigabytes 8. The companion post — IndexedDB vs localStorage: What Your Browser Can Store — walks the localStorage case in detail 9. The short version: localStorage is synchronous, string-only, capped at 5 mebibytes 10. That is a configuration store, not a database.

The Origin Private File System (OPFS) is the future story, not the current one. MDN calls OPFS "highly optimized for performance, especially with the addition of dedicated FileSystemSyncAccessHandle access" 11. RxDB's benchmarks suggest OPFS sync handles are roughly 4× faster than IndexedDB for the read-heavy workloads where wa-sqlite shines 12. The trade-off is that OPFS exposes a filesystem, not a database — no indexes, no transactions, no cursors. You bring your own query engine. For a notes app with a few thousand records and queries by updatedAt or folderId, IndexedDB is the right ceiling. OPFS is the upgrade you reach for when complex SQL or sustained multi-megabyte writes demand it 13.

Cache Storage is the third storage in play and the easiest to confuse with IndexedDB. Pete LePage's web.dev guidance is the rule worth memorizing: "For the network resources necessary to load your app, use the Cache Storage API (part of service workers)" and "For other data, use IndexedDB (with a promises wrapper)" 14. Cache Storage holds responses. IndexedDB holds records. They are different stores with different APIs, and a PWA uses both.

Why Dexie, not raw IDB or idb or RxDB

Dexie is the choice when you want a fluent, transactional, TypeScript-friendly API over IndexedDB without inheriting a heavier abstraction. Its README phrases the relationship cleanly: "IndexedDB is the portable database for all browser engines. Dexie.js makes it fun and easy to work with" 2. The library sits at 14.3k stars and is "widely used by 100,000 of web sites" 2.

Three other libraries belong in the comparison, and each is the right choice for a different shape of app. Jake Archibald's idb is "a tiny (~1.19kB brotli'd) library that mostly mirrors the IndexedDB API, but with small improvements that make a big difference to usability" 15 — keep it when you want the raw IndexedDB surface, just promise-shaped. Mozilla's localForage presents a localStorage-flavored facade for code already written against the synchronous interface 16. RxDB is "a fast, local-first, reactive database for JavaScript applications" 17 — a much larger abstraction with built-in replication, plugins for SQLite/Dexie/IndexedDB backends, and a steeper learning curve. PouchDB is a different shape — a sync-first database modeled on CouchDB, not a wrapper around IndexedDB — and out of scope for this post.

Pick thisWhen you want
DexieTyped tables, indexed queries, real transactions, schema migrations, optional reactive React queries — without a replication framework.
idbThe raw IndexedDB surface, just promise-shaped. ~1.19 kB. Zero opinions.
localForageA localStorage-flavored facade for code already written against the synchronous interface.
RxDBSync as a configuration choice. Swappable storage adapters (IndexedDB, OPFS, SQLite) and plugin-driven replication.

The Dexie sweet spot is an app that needs typed tables, indexed queries, real transactions, schema migrations, and reactive React queries — without committing to a full replication framework. The trade-off Dexie makes is opinion density: it is friendly enough to feel like a library, structured enough to feel like a database, and small enough to read end-to-end on a Sunday.

Schema design

A Dexie schema is one method call per version, one schema string per table, and the smallest set of indexes that answers your real queries. The official stores() docs phrase it directly: each key represents a table name, and each value represents the primary key followed by the indexed properties 18. Every other rule follows from that one sentence.

The schema DSL uses a handful of characters. Per the official docs: ++ for an auto-incremented primary key, & for a unique index, * for a multi-entry index, [A+B] for a compound index or compound primary key, and a leading comma if there is no primary key but you still want indexes 18. The full example from the docs shows all five at once:

db.version(1).stores({
    friends: '++id,name,shoeSize',
    pets: 'id, name, kind',
    cars: '++, name',
    enemies: ',name,*weaknesses',
    users: 'meta.ssn, addr.city',
    people: '[name+ssn], &ssn'
});

Two design rules earn their weight. First, do not index fields you do not query — every extra index slows writes and grows the database file. Second, index booleans only when you query them as filters in cursors; a pinned: true | false flag that you scan with .filter() is fine 19. The following example follows both rules:

import Dexie, { type EntityTable } from 'dexie';

interface Note {
  id: string;
  title: string;
  body: string;
  folderId: string | null;
  pinned: boolean;
  archived: boolean;
  created: number;
  modified: number;
  tags: string[];
  schemaVersion: number;
  order: number;
  type: 'note' | 'draw';
}

interface Folder {
  id: string;
  name: string;
  order: number;
}

export class NotesDB extends Dexie {
  notes!: EntityTable<Note, 'id'>;
  folders!: EntityTable<Folder, 'id'>;

  constructor() {
    super('mynotes');
    this.version(1).stores({
      notes: 'id, title, folderId, pinned, archived, created, modified, *tags, schemaVersion, order, type',
      folders: 'id, name, order',
    });
  }
}

export const db = new NotesDB();

EntityTable<Note, 'id'> is the Dexie 4 TypeScript pattern — every table is typed by its row interface and its primary-key field name 20. The schema string says id is the primary key; the indexes are the comma-separated fields that follow; *tags is multi-entry, which means the cursor will yield notes that contain a given tag value rather than notes whose tags array exactly equals a value. A real schema grows longer as the app matures — more tables, more fields, more migrations.

Reactive queries with useLiveQuery

useLiveQuery is Dexie's React hook for treating IndexedDB as a reactive source — the component re-renders when matching rows change. The package is published separately as dexie-react-hooks, installed alongside dexie 21. The documentation describes the hook in one sentence: "Observe IndexedDB data in your React component. Make the component re-render when the observed data changes" 22.

The signature is small. The first argument is a function returning a Dexie query; the second optional argument is a dependency array; the third optional argument is a default value to return before the first result arrives 22:

export function useLiveQuery<T, TDefault = undefined>(
  querier: () => Promise<T> | T,
  deps?: any[],
  defaultResult?: TDefault
): T | TDefault;

In practice that becomes a one-line component:

import { useLiveQuery } from 'dexie-react-hooks';
import { db } from './db';

export function RecentNotes({ days = 7 }: { days?: number }) {
  const cutoff = Date.now() - days * 24 * 60 * 60 * 1000;
  const notes = useLiveQuery(
    () => db.notes.where('modified').above(cutoff).reverse().sortBy('modified'),
    [days, cutoff],
  );
  if (!notes) return null;
  return (
    <ul>
      {notes.map((n) => (
        <li key={n.id}>{n.title}</li>
      ))}
    </ul>
  );
}

Two details determine whether this code feels right or wrong. First, the dependency array works like useEffect's — when days or cutoff changes, the query is re-issued. Forget the deps array and your hook captures the first cutoff forever. Second, the initial render returns undefined until the first result resolves, which the Dexie tutorial calls out plainly: "The result will be undefined momentarily before the very initial result arrives" 21. Components that depend on notes.length need a null guard, or the third-argument default — useLiveQuery(querier, deps, []) — so the first paint sees an empty array rather than undefined.

PatternUse
useLiveQuery(() => db.t.toArray())All rows, reactive.
useLiveQuery(() => db.t.where('x').above(v).toArray(), [v])Filtered with deps.
useLiveQuery(querier, deps, [])With default to avoid undefined on first paint.

The under-the-hood mechanic is the one that retires the most code. Dexie subscribes the hook to IndexedDB write events and re-runs the querier when affected stores change 22. There is no manual cache invalidation, no revalidateOnFocus, no queryClient.invalidateQueries. The single source of truth is the database; views are projections; React renders. The cost is that complex composite views — for example, a sidebar that joins notes, folders, and tags — need one useLiveQuery per composition, or a single query that fetches the joined shape inside the function.

Transactions and the "Transaction Inactive" trap

Transactions in IndexedDB are short-lived — alive only while the JavaScript task that opened them is on the stack, committed when control returns to the event loop. Dexie wraps that lifecycle with db.transaction() plus a custom Dexie.Promise that maintains the transaction context across awaits. The docs phrase the function plainly: "Start a database transaction" 23.

The shape:

await db.transaction('rw', db.notes, db.folders, async () => {
  const folder = await db.folders.get(folderId);
  if (!folder) throw new Error('Folder gone');
  await db.notes.put({
    id: crypto.randomUUID(),
    title: 'Untitled',
    body: '',
    folderId,
    pinned: false,
    archived: false,
    created: Date.now(),
    modified: Date.now(),
    tags: [],
    schemaVersion: 1,
    order: 0,
    type: 'note',
  });
  folder.order = (folder.order ?? 0) + 1;
  await db.folders.put(folder);
});

The first argument is the mode — 'rw' for readwrite or 'r' for readonly per the docs 23. The next arguments are the tables the scope touches. The final argument is the function that runs inside the transaction. If it throws, the transaction aborts; the writes do not land.

The trap that earns developer-hours: do not mix native promises into a transaction. The Dexie docs explain the underlying conflict — "an incompatibility between the IndexedDB specification and the Promise specification" — and the practical effect: "any further call to db will fail with 'Transaction Inactive' error" if you await a non-Dexie promise inside a transaction 24. Dexie patches the global Promise within the transaction zone, so an in-flight await fetch(...) will not break things in Chrome, but it will lose the transaction context on browsers without the patch. The safe pattern: any I/O outside the database happens before or after the transaction, never inside. Reads, writes, and db.* calls inside; network and timers outside.

Migrations: the version() chain in production

Dexie's migration model is a chain of version().stores().upgrade() calls — each version represents an irreversible step forward, and the upgrade callback runs once per user, atomically, the first time they open a newer schema. The official upgrade example demonstrates the pattern that handles 90% of real cases 25:

.upgrade (trans => {
    var YEAR = 365 * 24 * 60 * 60 * 1000;
    return trans.table("friends").toCollection().modify (friend => {
        friend.birthdate = new Date(Date.now() - (friend.age * YEAR));
        delete friend.age;
    });
});

Collection.modify() is the workhorse — per the docs, it "Modifies all objects in the table subset represented by this Collection instance" 26. Inside an upgrade(), you call it through trans.table(name).toCollection().modify(callback) so the iteration runs inside the version-change transaction Dexie has already opened.

A real app accumulates many schema versions. For example, a note app might evolve like this:

v1 → v3 (+order) → v6 (+type, +drawData) → v8 (+isPublic) → v10 (+pendingSync) → v11 (+userId)

The pattern across all eleven is identical: declare the new schema in .stores(), then in .upgrade() walk the affected tables with trans.table(name).toCollection().modify() and set the new field's default. Three rules earn their weight in production:

The order of operations matters too. Dexie calls db.open() automatically on the first query 27, which is the moment the upgrade chain runs. If your app hits the database during render — and most do, through useLiveQuery — the first render is also the first migration. A user upgrading from a six-month-old build can step through five schema versions in a single page load. Test that path. Twice.

Bulk writes and the 80-millisecond rule

Throughput on IndexedDB is dominated by transaction count, not row count. RxDB's measurement is the one to cite: "inserting 1k documents into IndexedDB takes about 80 milliseconds" inside a single transaction, versus "about 2 seconds" with "one transaction per write" 28. Same 1,000 rows, 25× slower because each one was its own transaction.

OperationTimeTransactions
1,000 inserts in one bulkPut()~80 ms1
1,000 inserts as put() in a loop~2,000 ms1,000

The Dexie API exposes the fast path through Table.bulkPut(). The docs phrase it bluntly: "Add all given objects to the store. If you have a large number of objects to add to the object store, bulkPut() is faster than doing put() in a loop" 29. The signature is:

table.bulkPut(items, keys?, options?)

In an import pipeline — restoring a backup, ingesting a zip of markdown files — the pattern that pays for itself within ten records:

async function importNotes(parsed: Note[]) {
  await db.transaction('rw', db.notes, async () => {
    await db.notes.bulkPut(parsed);
  });
}

The transaction wrapper is redundant in this exact case — bulkPut() opens one transaction internally — but it stays when you add a sibling write to a different table inside the same atomic operation. The mental model worth keeping: every distinct unit of "this must succeed or fail together" is one transaction; everything else is independent.

Sync — when to add Yjs or Automerge or Loro, and when to skip

Sync is a separate problem from storage. Three real options stand up in 2026: Yjs, Automerge, and Loro — all CRDT libraries (Conflict-free Replicated Data Types) that let two replicas converge to the same state without a central coordinator. The hard part is no longer the algorithm; it is the transport, auth, storage adapter, and testing.

Yjs is the most established. Its tagline is direct: "A CRDT framework with a powerful abstraction of shared data" 6. The repository sits at 21.8k stars 6. Yjs persists to the browser through y-indexeddb, "an IndexedDB database provider for Yjs" that lets you "store your shared data persistently in the browser" 30:

import * as Y from 'yjs';
import { IndexeddbPersistence } from 'y-indexeddb';

const ydoc = new Y.Doc();
const provider = new IndexeddbPersistence('note-' + noteId, ydoc);

provider.on('synced', () => {
  console.log('content from the database is loaded');
});

Automerge is the other major player and the most aligned with the Ink & Switch lineage. Its homepage frames the product line cleanly: "Automerge is a local-first sync engine for multiplayer apps that works offline, prevents conflicts, and runs fast" 31. Loro is the newest and the Rust-backed contender: "Make your JSON data collaborative and version-controlled with CRDTs" 32, with WebAssembly bindings for JavaScript 32.

The honest answer for v1 of most apps is "do not add any of them yet." A single-user note app that stores in IndexedDB needs no CRDT. Add sync when you have a second device per user, not when you have a screenshot of a roadmap. Dexie Cloud is the other path — a managed sync service from the same team as Dexie — and the free tier is straightforward: "3 production users and 100 MB of storage" 33. The trade-off, as ever: managed sync is fast to ship and adds a vendor. CRDT-based sync is slower to ship and adds nothing.

That is the decision worth naming: pick the sync library that aligns with the editor's data model, not with your storage. For ProseMirror-based editors, Yjs is the natural fit because it integrates at the editor's data model rather than at the storage layer.

Service Worker, Cache API, and the Background Sync gap

The service worker is the second piece of an offline-first app — it makes the app shell load without a network. Serwist, which describes itself as "a fork of Workbox" 34, is a straightforward option. The model is unchanged from Workbox: precache the app shell at install, runtime-cache navigation requests, fall back to a cached index.html when offline.

Local-first PWAs use three layers: a service worker (Serwist) for the app shell, Cache Storage for network responses, and IndexedDB (via Dexie) for application data. The gap that surprises developers sits between the second and the third: Background Sync. The Background Synchronization API, per MDN, "enables a web app to defer tasks so that they can be run in a service worker once the user has a stable network connection" 35. The API is exactly what an offline-first app wants — queue a write, sync it later — and exactly what only Chromium-family browsers ship. Caniuse's data, as of 2026-05-16, records 76.71% global support, with full coverage in Chrome, Edge, Opera, and Samsung Internet, and zero support across Safari, iOS Safari, and Firefox 36. The durable framing: Background Sync is Chromium-family only. Building on it alone means building for two-thirds of the web and silently breaking for the other third.

The portable fallback is the one to write. The shape: on every mutation, write to IndexedDB and set a pendingSync: true flag on the record. On a visibilitychange to "visible" and on navigator.onLine === true, drain the queue. The service worker plays no role in the sync; it only makes the app shell load offline. This is not elegant. It is the only design that works on iOS in 2026.

async function saveNote(note: Note) {
  await db.notes.put({ ...note, modified: Date.now(), pendingSync: true });
  if (navigator.onLine) await drainSyncQueue();
}

async function drainSyncQueue() {
  const pending = await db.notes.where('pendingSync').equals(true).toArray();
  for (const note of pending) {
    try {
      await pushToServer(note);
      await db.notes.update(note.id, { pendingSync: false, lastSyncedAt: Date.now() });
    } catch {
      // Leave pendingSync true; next visibilitychange will retry.
    }
  }
}

The boolean field in this example — pendingSync — is exactly the kind of value to not index unless you have to. Dexie's .where('pendingSync').equals(true) works against an index, so this query needs it on the schema string. The trade-off shows the rule: index a boolean only when you build a queue against it. Index only the booleans that gate work queues; filter the rest through .filter().

Testing IndexedDB code with fake-indexeddb

Tests that touch IndexedDB run against fake-indexeddb — "A pure JS in-memory implementation of the IndexedDB API" 37, currently at v6.2.5 (7 November 2025) 37. The setup is one import in a Vitest or Jest configuration. For Vitest, add it to setupFiles; for Jest, the equivalent setting per the README is:

{
    "setupFiles": [
        "fake-indexeddb/auto"
    ]
}

The fake-indexeddb/auto entry installs the polyfill globally — indexedDB, IDBKeyRange, and friends — so Dexie code runs against it transparently. Tests then write the same Dexie code they would in production:

import { describe, it, expect, beforeEach } from 'vitest';
import { db } from '../db';
import type { Note } from '../db';

function makeNote(overrides: Partial<Note> = {}): Note {
  return {
    id: crypto.randomUUID(),
    title: '',
    body: '',
    folderId: null,
    pinned: false,
    archived: false,
    created: Date.now(),
    modified: Date.now(),
    tags: [],
    schemaVersion: 1,
    order: 0,
    type: 'note',
    ...overrides,
  };
}

describe('notes table', () => {
  beforeEach(async () => {
    await db.notes.clear();
  });

  it('returns notes modified within the cutoff', async () => {
    const now = Date.now();
    await db.notes.bulkPut([
      makeNote({ id: 'a', title: 'Recent', modified: now - 1000 }),
      makeNote({ id: 'b', title: 'Old', modified: now - 30 * 24 * 60 * 60 * 1000 }),
    ]);
    const recent = await db.notes
      .where('modified')
      .above(now - 7 * 24 * 60 * 60 * 1000)
      .toArray();
    expect(recent).toHaveLength(1);
    expect(recent[0].id).toBe('a');
  });
});

Two real gotchas come up repeatedly. First, fake-indexeddb is in-memory only; the data is gone between processes. Always reset state in a beforeEach, not just per-suite. Second, useLiveQuery is harder to test than direct queries because its subscription model is awkward to drive synchronously. The pragmatic pattern is to test the underlying Dexie queries directly with fake-indexeddb and test the component composition with React Testing Library and a mocked hook. A real project exercises every schema migration against fake-indexeddb in CI before shipping.

Persistent storage and the Safari eviction clock

navigator.storage.persist() is the one Web Storage API call most offline-first apps forget to make. Per MDN, it "requests permission to use persistent storage, and returns a Promise that resolves to true if permission is granted and bucket mode is persistent, and false otherwise" 38. Persistent storage opts the origin out of LRU eviction.

Pete LePage's article on the topic, last updated 12 May 2020, lays out the cross-browser behavior plainly. Chrome and Chromium-derived browsers grant the request automatically based on engagement signals — bookmarking, installation, notification permissions 39. Firefox prompts the user explicitly when the call is made 39. Safari does neither in the same way; storage on Safari has a separate eviction clock — seven days of no user interaction with the site, per John Wilander's WebKit post 40 — that persist() does not override. PWAs installed to the home screen are exempt from the Safari clock 40; ordinary websites are not.

The portable call:

async function requestPersistence(): Promise<boolean> {
  if (!navigator.storage || !navigator.storage.persist) return false;
  return await navigator.storage.persist();
}

Where to call it: at the first meaningful interaction, not on page load. Chrome's heuristic for granting persistence is engagement-based, and calling it at app boot — before the user has done anything — returns false and then never gets called again. Defer it until after the first save, the first edit, the first navigation. The browser will be more likely to say yes, and the user has earned the prompt by then.

Quota, eviction, and graceful degradation

Quota is per-origin, per-browser, and not a flat number. Pete LePage's web.dev guide gives the operating numbers: Chromium browsers permit "up to 60% of the total disk space available on the device" per origin 14; Safari allows roughly 1 GiB before prompting 14; Firefox grants up to 50% of free disk once persisted 41.

async function getQuotaUsage(): Promise<{ usedMB: number; quotaMB: number } | null> {
  if (!navigator.storage || !navigator.storage.estimate) return null;
  const { usage = 0, quota = 0 } = await navigator.storage.estimate();
  return { usedMB: usage / 1024 / 1024, quotaMB: quota / 1024 / 1024 };
}

Graceful degradation when the quota is hit means three things. First, catch QuotaExceededError on writes 42 and surface a user-visible explanation, not a stack trace. Second, offer an export — fflate for ZIP is the standard in 2026 43 — so the user can move bytes off the device. Third, never silently drop the write; queue it, name it, let the user delete other data and retry. A note app that loses a note to a quota error is worse than a note app that refuses to open.

What this post does not cover

The sync engine internals of Dexie Cloud, Yjs awareness protocols, OPFS-direct or wa-sqlite storage layers, and the conflict-resolution semantics of three-way CRDT merges are deliberately out of scope. The goal here is the layer between IndexedDB and the React tree — schema, queries, transactions, migrations, shell. Everything above and below has its own books.

Architecture notes

Three opinionated decisions earn their weight in production:

Frequently Asked Questions

What version of Dexie should I use in 2026? The latest stable, currently v4.4.2 (31 March 2026) 3. The 4.x line added IndexedDB 3.0 getAll() optimization, Yjs integration, and Blob/string offloading in 4.4.1 3. Pin to the major version and let minor patches flow.

Does Dexie work in Web Workers? Yes. Dexie runs in the main thread, Web Workers, Shared Workers, and Service Workers — any context with indexedDB. The official docs note db.open() is called automatically on first query in any of those contexts 27. The transaction-inactive trap 24 is the same in workers, so the rule about not awaiting non-Dexie promises inside a transaction applies identically.

Can I use Dexie without TypeScript? Yes. Dexie shipped as JavaScript for years before TypeScript became default. The schema DSL and the fluent query API are JS-native 18. TypeScript adds typed table rows via EntityTable<T, 'id'> 20, which is worth it for a real codebase but not required.

Is IndexedDB cleared when a user clears cookies? Browser-specific. Chrome and Firefox clear all site data — including IndexedDB — when the user clears "cookies and other site data" 44. Safari's seven-day eviction is a separate, automatic clock that fires without user action when the site has not been visited 40. Persistent storage (via navigator.storage.persist()) protects against LRU eviction in Chrome and Firefox; it does not override a deliberate user-initiated clear 38.

Do I need a service worker to be offline-first? For the app shell, yes — without one, the page fails to load when the network is gone. For data, no — IndexedDB works offline by default, with or without a service worker 14. Serwist or Workbox handle the shell; Dexie handles the data; they are independent layers.

What happens if a Dexie migration throws? The transaction aborts and the database stays at the previous version. The user reopens the app and hits the same error on every load. The pattern that survives this is to write migrations defensively — check if (record.field === undefined) before mutating, never assume — and to test each migration against fake-indexeddb in CI before shipping.

Should I use Dexie Cloud, Yjs, or build my own sync? Dexie Cloud is the fastest path to a running sync layer — the free tier covers "3 production users and 100 MB of storage" 33 — at the cost of a vendor. Yjs gives full CRDT semantics with no vendor and integrates cleanly with editors like Milkdown 6. Building your own is rarely correct; the sync surface is larger than it looks. Pick the one whose data model matches your editor's, not the one whose marketing page matches your aesthetic.

Closing

Offline-first is harder than it looks because the failure modes are quiet. A localStorage cap silently swallows the 5 MiB-th write. A fetch() in a Dexie transaction silently breaks the next call. A missing useLiveQuery dep silently freezes a view at the first cutoff. The architecture is small. The discipline is everything.

Dexie does not solve any of those problems by itself. It makes the surface small enough that you can keep the discipline in your head — version().stores().upgrade() for migrations, db.transaction('rw', ...) for atomicity, useLiveQuery for reactive reads, bulkPut for batched writes, and a service worker for the shell. Five concepts. Two hundred lines of database code for a real note app. Eleven migrations across a year of shipping 45. The whole stack fits in one mental model.

The stack above is small. The discipline is everything. That discipline is what MNMNOTE (mnmnote.com) is built around — it opens in your browser, stores nothing on a server, and works at airplane altitude.


References (verification queue)

Grouped by tier. URLs verified live as of 2026-05-16.

Tier 6 — Standards / specifications

Tier 1 — Academic / canonical

Tier 1 — Engineering / primary technical sources

Tier 3 — Industry / community references

Tier 4 — Founder / authoritative voices

Internal references

Tier 6 (continued) — MDN reference index

Tier 1 (continued) — Engineering blogs

Tier 1 (continued) — Dexie documentation deep-references

Tier 5 — Community / viral precedents

Tier 1 (continued) — Library ecosystem

Tier 2 — Mainstream technical references

Footnotes

  1. W3C. Indexed Database API 3.0. Editor's Draft, 13 August 2025. https://www.w3.org/TR/IndexedDB/ and the editor's draft at https://w3c.github.io/IndexedDB/. Accessed 2026-05-16. ↩

  2. GitHub. dexie/Dexie.js README. "A Minimalistic Wrapper for IndexedDB." "IndexedDB is the portable database for all browser engines. Dexie.js makes it fun and easy to work with." 14.3k stars; "widely used by 100,000 of web sites." https://github.com/dexie/Dexie.js. Accessed 2026-05-16. ↩ ↩2 ↩3

  3. GitHub. dexie/Dexie.js — releases. v4.4.2 released 31 March 2026; v4.4.1 (19 March 2026) introduced Blob/String Offloading for Dexie Cloud; v4.3.0 (30 January 2026) added Social Authentication. https://github.com/dexie/Dexie.js/releases. Accessed 2026-05-16. ↩ ↩2 ↩3

  4. Kleppmann, M., Wiggins, A., van Hardenberg, P., & McGranaghan, M. (2019). Local-first software: You own your data, in spite of the cloud. Onward! 2019 / Ink & Switch. Seven ideals: "No spinners: your work at your fingertips"; "Your work is not trapped on one device"; "The network is optional"; "Seamless collaboration with your colleagues"; "The Long Now"; "Security and privacy by default"; "You retain ultimate ownership and control." https://www.inkandswitch.com/essay/local-first/. Accessed 2026-05-16. ↩ ↩2 ↩3

  5. Kleppmann, M. Local-first software. Personal site. https://martin.kleppmann.com/. Accessed 2026-05-16. ↩

  6. GitHub. yjs/yjs. "A CRDT framework with a powerful abstraction of shared data." 21.8k stars. "Document updates are commutative and idempotent." "Changes are automatically distributed to other peers and merged without merge conflicts." https://github.com/yjs/yjs. Accessed 2026-05-16. ↩ ↩2 ↩3 ↩4

  7. GitHub. automerge/automerge. CRDT library; local-first sync engine. https://github.com/automerge/automerge. Accessed 2026-05-16. ↩

  8. van Kesteren, A. (editor). Storage Standard. WHATWG. https://storage.spec.whatwg.org/. Accessed 2026-05-16. ↩

  9. Internal — MNMNOTE blog post 08: IndexedDB vs localStorage: What Your Browser Can Store. Reference for the storage-class comparison this post builds on. https://blog.mnmnote.com/posts/indexeddb-vs-localstorage. ↩

  10. WHATWG. HTML Living Standard — §Web Storage. https://html.spec.whatwg.org/multipage/webstorage.html. Accessed 2026-05-16. ↩

  11. MDN. Origin private file system. "Highly optimized for performance, especially with the addition of dedicated FileSystemSyncAccessHandle access." Baseline since March 2023. https://developer.mozilla.org/en-US/docs/Web/API/File_System_API/Origin_private_file_system. Accessed 2026-05-16. ↩

  12. RxDB. LocalStorage vs. IndexedDB vs. Cookies vs. OPFS vs. WASM-SQLite. Benchmarks across browser storage APIs. https://rxdb.info/articles/localstorage-indexeddb-cookies-opfs-sqlite-wasm.html. Accessed 2026-05-16. ↩

  13. GitHub. sqlite/sqlite-wasm. "SQLite Wasm conveniently wrapped as an ES Module." OPFS backend in worker mode. https://github.com/sqlite/sqlite-wasm. Accessed 2026-05-16. ↩

  14. LePage, P. Storage for the web. web.dev. Last updated 23 September 2024. "For the network resources necessary to load your app, use the Cache Storage API (part of service workers)." "For other data, use IndexedDB (with a promises wrapper)." Chrome 60% per-origin quota; Safari ~1 GiB. https://web.dev/articles/storage-for-the-web. Accessed 2026-05-16. ↩ ↩2 ↩3 ↩4

  15. GitHub. jakearchibald/idb. "This is a tiny (~1.19kB brotli'd) library that mostly mirrors the IndexedDB API, but with small improvements that make a big difference to usability." 7.3k stars. https://github.com/jakearchibald/idb. Accessed 2026-05-16. ↩

  16. GitHub. localForage/localForage. "A fast and simple storage library for JavaScript." 25.8k stars; wraps IndexedDB, WebSQL, localStorage. https://github.com/localForage/localForage. Accessed 2026-05-16. ↩

  17. GitHub. pubkey/rxdb. "A fast, local-first, reactive database for JavaScript applications." 23.2k stars. https://github.com/pubkey/rxdb. Accessed 2026-05-16. ↩

  18. Dexie.org. Version.stores(). "Specifies tables to be added, altered or deleted in this version. Each key in the schemaDefinition argument represents a table name and each value represents the primary key followed by the list of indexed properties." Schema syntax: ++ auto-incremented PK, & unique index, * multi-entry index, [A+B] compound index. https://dexie.org/docs/Version/Version.stores(). Accessed 2026-05-16. ↩ ↩2 ↩3

  19. Dexie.org. Issue: Boolean indexes in IndexedDB. Boolean values do not produce valid IndexedDB keys; filter through .filter() or use 0/1 encoding. https://dexie.org/docs/Boolean. Accessed 2026-05-16. ↩

  20. Dexie.org. Typescript. EntityTable<T, 'id'> pattern; class extends Dexie with typed table properties. https://dexie.org/docs/Typescript. Accessed 2026-05-16. ↩ ↩2

  21. Dexie.org. Tutorial — React. "yarn add dexie / yarn add dexie-react-hooks." "The result will be undefined momentarily before the very initial result arrives." https://dexie.org/docs/Tutorial/React. Accessed 2026-05-16. ↩ ↩2

  22. Dexie.org. dexie-react-hooks — useLiveQuery(). "Observe IndexedDB data in your React component. Make the component re-render when the observed data changes." Signature: useLiveQuery<T, TDefault=undefined>(querier, deps?, defaultResult?). https://dexie.org/docs/dexie-react-hooks/useLiveQuery(). Accessed 2026-05-16. ↩ ↩2 ↩3

  23. Dexie.org. Dexie.transaction(). "Start a database transaction. When accessing the database within the given scope function, any Table-based operation will execute within the current transaction." Modes: 'rw' (readwrite), 'r' (readonly). https://dexie.org/docs/Dexie/Dexie.transaction(). Accessed 2026-05-16. ↩ ↩2

  24. Dexie.org. Promise / Transaction Inactive. "An incompatibility between the IndexedDB specification and the Promise specification." "Any further call to db will fail with 'Transaction Inactive' error." https://dexie.org/docs/Promise/Promise. Accessed 2026-05-16. ↩ ↩2

  25. Dexie.org. Version.upgrade(). Upgrade example: .upgrade(trans => { ... return trans.table("friends").toCollection().modify(friend => { friend.birthdate = ...; delete friend.age; }); }). https://dexie.org/docs/Version/Version.upgrade(). Accessed 2026-05-16. ↩

  26. Dexie.org. Collection.modify(). "Modifies all objects in the table subset represented by this Collection instance." https://dexie.org/docs/Collection/Collection.modify(). Accessed 2026-05-16. ↩

  27. Dexie.org. Dexie.open(). "Open a database connection. After the call to open() you must not call Dexie.version() anymore." "By default, db.open() will be called automatically on first query to the db." https://dexie.org/docs/Dexie/Dexie.open(). Accessed 2026-05-16. ↩ ↩2

  28. RxDB. Slow IndexedDB. "Inserting 1k documents with one transaction per write, takes about 2 seconds." "Inserting 1k documents into IndexedDB takes about 80 milliseconds" with a single transaction. "The limiting factor to IndexedDB performance is the transaction handling, not the data throughput." https://rxdb.info/slow-indexeddb.html. Accessed 2026-05-16. ↩

  29. Dexie.org. Table.bulkPut(). "Add all given objects to the store. If you have a large number of objects to add to the object store, bulkPut() is faster than doing put() in a loop." Signature: table.bulkPut(items, keys?, options?). https://dexie.org/docs/Table/Table.bulkPut(). Accessed 2026-05-16. ↩

  30. GitHub. yjs/y-indexeddb. "IndexedDB database provider for Yjs" — "store your shared data persistently in the browser." Example: new IndexeddbPersistence(docName, ydoc). https://github.com/yjs/y-indexeddb. Accessed 2026-05-16. ↩

  31. Automerge. Homepage. "Automerge is a local-first sync engine for multiplayer apps that works offline, prevents conflicts, and runs fast." https://automerge.org/. Accessed 2026-05-16. ↩

  32. GitHub. loro-dev/loro. "Make your JSON data collaborative and version-controlled with CRDTs." Rust 89.9% of codebase; WebAssembly bindings for JavaScript. https://github.com/loro-dev/loro. Accessed 2026-05-16. ↩ ↩2

  33. Dexie. Dexie Cloud — pricing. Free tier: "3 production users and 100 MB of storage"; production plans from 3 euros/month. https://dexie.org/cloud/. Accessed 2026-05-16. ↩ ↩2

  34. Serwist docs. "A Swiss Army knife for service workers." "It is a fork of Workbox that came to be due to the its development being stagnated." https://serwist.pages.dev/ and https://serwist.pages.dev/docs. Accessed 2026-05-16. ↩

  35. MDN. Background Synchronization API. "Enables a web app to defer tasks so that they can be run in a service worker once the user has a stable network connection." https://developer.mozilla.org/en-US/docs/Web/API/Background_Synchronization_API. Accessed 2026-05-16. ↩

  36. caniuse.com. Background Sync API. As of 2026-05-16: 76.71% global support. Full support: Chrome 49+, Edge 79+, Opera 42+, Samsung Internet 5+. Zero support: Safari (all versions), Firefox (through v150), iOS Safari (all versions). https://caniuse.com/background-sync. Accessed 2026-05-16. ↩

  37. GitHub. dumbmatter/fakeIndexedDB. "A pure JS in-memory implementation of the IndexedDB API." v6.2.5 released 7 November 2025. https://github.com/dumbmatter/fakeIndexedDB. Accessed 2026-05-16. ↩ ↩2

  38. MDN. StorageManager.persist(). "Requests permission to use persistent storage, and returns a Promise that resolves to true if permission is granted and bucket mode is persistent, and false otherwise." https://developer.mozilla.org/en-US/docs/Web/API/StorageManager/persist. Accessed 2026-05-16. ↩ ↩2

  39. LePage, P. Persistent storage. web.dev. Last updated 12 May 2020. Chrome grants persistence via engagement signals (bookmarking, installation, notification permissions); Firefox prompts the user; Safari uses a separate seven-day eviction model that persist() does not override. https://web.dev/articles/persistent-storage. Accessed 2026-05-16. ↩ ↩2

  40. Wilander, J. (24 March 2020). Full Third-Party Cookie Blocking and More. WebKit Blog. Seven-day cap on script-writable storage in Safari; PWAs installed to home screen exempt. https://webkit.org/blog/10058/full-third-party-cookie-blocking-and-more/. Accessed 2026-05-16. ↩ ↩2 ↩3

  41. MDN. Storage quotas and eviction criteria. Firefox: 10 GiB best-effort group; persistent up to 50% of disk, capped at 8 TiB. https://developer.mozilla.org/en-US/docs/Web/API/Storage_API/Storage_quotas_and_eviction_criteria. Accessed 2026-05-16. ↩

  42. MDN. QuotaExceededError. https://developer.mozilla.org/en-US/docs/Web/API/QuotaExceededError. Accessed 2026-05-16. ↩

  43. GitHub. 101arrowz/fflate. High-performance compression library; ~8 KB gzipped. https://github.com/101arrowz/fflate. Accessed 2026-05-16. ↩

  44. MDN. StorageManager.estimate(). https://developer.mozilla.org/en-US/docs/Web/API/StorageManager/estimate. Accessed 2026-05-16. ↩

  45. Dexie.org. Schema design and indexing guidance. https://dexie.org/docs/Version/Version.stores(). Accessed 2026-05-16. ↩