Dev.to WebDev 🛠 Dev 👁 0 📖 9 min read

IndexedDB in React: Offline-First Apps with WatermelonDB

Originally published at muhammadmoiz.dev. IndexedDB is the browser's built-in database. It is the right place to keep the data a React app needs to keep working when the network drops. You can use it directly through a

IndexedDB in React: Offline-First Apps with WatermelonDB

Originally published at muhammadmoiz.dev.

IndexedDB is the browser's built-in database. It is the right place to keep the data a React app needs to keep working when the network drops. You can use it directly through a small wrapper like idb for simple caching. If you need relations, reactive queries and two-way sync with a server, put WatermelonDB on top of it. This tutorial walks through both approaches, with code you can adapt.

I used WatermelonDB on browser storage to build the offline-first data layer of Oscar, a restaurant and retail POS. A POS can't stop taking orders just because the Wi-Fi went down. The patterns below are the ones I'd reach for again. If you want the product-level story first, read lessons from building an offline-first POS in React. This post is the hands-on developer version.

What is IndexedDB, and why not just use localStorage?

IndexedDB is an asynchronous, transactional object store that ships with every modern browser. You don't define tables with fixed columns. Instead you create object stores that hold JavaScript objects identified by a key. You add indexes on the fields you want to search by, and you read or write inside transactions. Anything the structured clone algorithm can copy, including Blobs and files, can be stored. It also works inside Web Workers, so heavy database work can stay off the main thread.

localStorage feels easier, but it has two problems for offline apps:

localStorage IndexedDB
API style Synchronous, blocks the main thread Asynchronous, event or promise based
Data Strings only Structured objects, Blobs, files
Querying Read by key only Indexes, key ranges, cursors
Size 5 MiB per origin A share of total disk (see below)
Transactions None Read-only and readwrite transactions

The 5 MiB figure comes from MDN's storage quota guide. A product catalogue, a few days of orders and some images will pass that quickly. IndexedDB quotas are far larger. Chromium browsers allow an origin up to 60% of total disk. Recent Safari versions (macOS 14 and iOS 17 onward) allow about 60% for browser apps. Firefox gives best-effort storage the smaller of 10% of the disk or 10 GiB.

How do you use IndexedDB in React without the boilerplate?

The raw API is built on request objects and onsuccess callbacks, which is awkward in modern code. The idb library by Jake Archibald wraps it in promises and adds TypeScript types. It is tiny, and version 8.0.4 was the latest on npm when I checked in November 2026.

npm install idb

Here is a small, typed data module for a list of orders:

// db.ts
import { openDB, type DBSchema } from "idb";

interface ShopDB extends DBSchema {
  orders: {
    key: string;
    value: {
      id: string;
      status: "pending" | "paid";
      total: number;
      updatedAt: number;
    };
    indexes: { by_status: string };
  };
}

export const dbPromise = openDB<ShopDB>("shop", 1, {
  upgrade(db) {
    const store = db.createObjectStore("orders", { keyPath: "id" });
    store.createIndex("by_status", "status");
  },
});

export async function saveOrder(order: ShopDB["orders"]["value"]) {
  const db = await dbPromise;
  await db.put("orders", { ...order, updatedAt: Date.now() });
}

export async function pendingOrders() {
  const db = await dbPromise;
  return db.getAllFromIndex("orders", "by_status", "pending");
}

A few things are worth knowing:

  • The schema only changes in upgrade. When you add a store or index, bump the version number and handle oldVersion inside upgrade. Never delete a store your users already have data in without migrating it.

  • Generate IDs on the device. crypto.randomUUID() lets you create records offline without asking the server for an ID. It also makes duplicate detection easy later.

  • Keep transactions short. A transaction closes once you stop giving it work, so don't await a network call in the middle of one.

In a component, read the data inside an effect and store it in state:

import { useEffect, useState } from "react";
import { pendingOrders } from "./db";

export function PendingOrders() {
  const [orders, setOrders] = useState<Awaited<ReturnType<typeof pendingOrders>>>([]);

  useEffect(() => {
    pendingOrders().then(setOrders);
  }, []);

  return <p>{orders.length} orders waiting to sync</p>;
}

This works well for caching and small offline features. It breaks down once your data has relations (an order with items, modifiers and payments) and many screens that must update the moment something changes. Then you are writing your own query layer, change tracking and sync protocol. That is what WatermelonDB already does.

Rows of black server racks in a data center
Photo: imgix on Unsplash

Setting up WatermelonDB on top of IndexedDB

WatermelonDB is a reactive database for React and React Native. On the web it runs through its LokiJS adapter, which can save data incrementally to IndexedDB. The current npm release is 0.28.0.

npm install @nozbe/watermelondb

It uses decorators for models, so your bundler needs the Babel decorators and class-properties plugins. The installation guide lists them. Start with a schema:

// model/schema.ts
import { appSchema, tableSchema } from "@nozbe/watermelondb";

export const schema = appSchema({
  version: 1,
  tables: [
    tableSchema({
      name: "orders",
      columns: [
        { name: "status", type: "string", isIndexed: true },
        { name: "total", type: "number" },
        { name: "created_at", type: "number" },
      ],
    }),
    tableSchema({
      name: "order_items",
      columns: [
        { name: "order_id", type: "string", isIndexed: true },
        { name: "name", type: "string" },
        { name: "qty", type: "number" },
      ],
    }),
  ],
});

Then create the adapter and the database. The adapter options are where most of the production problems get solved, so don't skip them:

// database.ts
import { Database } from "@nozbe/watermelondb";
import LokiJSAdapter from "@nozbe/watermelondb/adapters/lokijs";
import { schema } from "./model/schema";
import { migrations } from "./model/migrations";
import { Order, OrderItem } from "./model";

const adapter = new LokiJSAdapter({
  schema,
  migrations,
  dbName: "shop",
  useWebWorker: false,
  useIncrementalIndexedDB: true,
  onQuotaExceededError: () => showStorageFullBanner(),
  onSetUpError: () => offerReloadOrLogout(),
  extraIncrementalIDBOptions: {
    // Another tab overwrote this tab's data: sync now, warn if offline
    onDidOverwrite: () => syncNow(),
    // The database was deleted in another tab (e.g. logout)
    onversionchange: () => window.location.reload(),
  },
});

export const database = new Database({
  adapter,
  modelClasses: [Order, OrderItem],
});

The multi-tab handlers matter more than they look. Staff often have the same app open in two tabs. If you ignore those callbacks, one tab can quietly overwrite what the other wrote.

Reading and writing records

Every write goes through database.write, which keeps changes consistent:

import { Q } from "@nozbe/watermelondb";

export async function createOrder(items: { name: string; qty: number }[]) {
  await database.write(async () => {
    const order = await database.get<Order>("orders").create((o) => {
      o.status = "pending";
      o.total = 0;
    });
    for (const item of items) {
      await database.get<OrderItem>("order_items").create((i) => {
        i.order.set(order);
        i.name = item.name;
        i.qty = item.qty;
      });
    }
  });
}

export const pendingQuery = () =>
  database.get<Order>("orders").query(Q.where("status", "pending"));

The real benefit is that queries are observable. Call pendingQuery().observe() (or use the withObservables helper) and any component reading it re-renders when a matching record changes, whether a cashier made the change or a sync did. You stop passing refresh callbacks around.

For synced apps, delete with markAsDeleted() so the deletion reaches the server. Use destroyPermanently() only for data that never leaves the device.

How does sync work between IndexedDB and your backend?

WatermelonDB's synchronize() function needs two things from you:

  1. pullChanges({ lastPulledAt }) calls your API and returns { changes, timestamp }. changes holds everything created, updated or deleted on the server since the last pull.
  2. pushChanges({ changes }) sends local changes to your API. It must reject if the server fails to apply them.
import { synchronize } from "@nozbe/watermelondb/sync";

export async function syncNow() {
  await synchronize({
    database,
    migrationsEnabledAtVersion: 1,
    pullChanges: async ({ lastPulledAt, schemaVersion }) => {
      const res = await fetch(
        `/api/sync?since=${lastPulledAt ?? 0}&schema=${schemaVersion}`,
      );
      if (!res.ok) throw new Error("Pull failed");
      return res.json(); // { changes, timestamp }
    },
    pushChanges: async ({ changes, lastPulledAt }) => {
      const res = await fetch(`/api/sync?last_pulled_at=${lastPulledAt}`, {
        method: "POST",
        body: JSON.stringify(changes),
      });
      if (!res.ok) throw new Error("Push failed");
    },
  });
}

The changes payload is grouped by table, with created, updated and deleted lists. Deleted records are sent as IDs only, and fields use the raw column names from your schema. Your backend has to keep its side of the deal:

  • Track changes on the server. Add a last_modified column to every table and set it on every write. Pull returns rows where it is newer than lastPulledAt. Ignore any value the client sends for it.

  • Track deletions. Use a soft-delete flag or a table of deleted IDs. Otherwise devices never learn that a record is gone.

  • Make push all-or-nothing. Apply the whole batch in one database transaction. If anything fails, roll back and return an error. A half-applied order is worse than one that retries.

  • Reject stale pushes. If a record changed on the server after the client's lastPulledAt, fail the push. The client then pulls, resolves the conflict and pushes again. That's why the docs suggest retrying a failed sync once.

  • Never run two syncs at once. Guard syncNow() with a flag. Call it when the app starts, on the browser's online event and on a timer.

Production checklist for an offline-first React app

The tutorial code works on your laptop. These are the things that decide whether it survives real users:

  • Ask for persistent storage. By default, browser storage is "best effort" and can be evicted when the device is low on space. Call navigator.storage.persist() after the user has used the app for a while. Firefox shows a prompt. Chrome and Safari decide on their own based on how the user engages with the site.

  • Watch your usage. navigator.storage.estimate() gives a rough figure for usage and quota. Use it to prune old records before you hit QuotaExceededError.

  • Handle quota and setup errors in the UI, not just in the console.

  • Plan for Safari's 7-day rule. With tracking prevention on, Safari deletes script-written storage for an origin the user hasn't interacted with in the last 7 days of browser use. Treat the local database as a cache of the server, never as the only copy.

  • Remember that eviction is all-or-nothing. When an origin is evicted, its IndexedDB, Cache API and other storage go together. Sync often so there is little unsynced data at risk.

  • Write migrations from day one and never delete old ones. Users may open an app version that is months old.

  • Test the bad days. Turn off the network mid-order, open two tabs, fill the disk, log out in one tab. Those are the bugs real users will find.

Don't store secrets in IndexedDB: Anything in IndexedDB can be read by any script running on your origin, including a malicious third-party script. Keep auth tokens short-lived and never cache data the current user isn't allowed to see.

What this means if you own the app

Offline-first is a product decision before it is a technical one. If your users work in kitchens, warehouses, shops, field sites or anywhere with patchy signal, a "you're offline" screen costs you sales and trust. Building it properly means designing the data model and sync rules first, then the screens. Adding it to an existing app later is possible, but usually means reworking how every feature reads and writes data.

A rough guide:

  • Caching a few screens or drafts: IndexedDB with idb is enough.

  • The whole app must keep working offline, with relational data and multiple devices: use WatermelonDB (or a similar sync engine) and budget real time for the backend sync endpoints.

  • Not sure: start by listing what your users must be able to do with no connection. That list decides the architecture.

If you're planning an app that has to work offline, or your current one loses data when the connection drops, see how I approach offline-first app development. For point of sale systems specifically, there is also POS development.

Sources

I'm Muhammad Moiz, a full-stack developer who builds web apps, SaaS and POS systems, and takes AI-built apps (Lovable, Bolt, Replit) to production. Get in touch.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.