Offline-first storage
Read and write a store on the device first; the network is a sync step that runs when a request can succeed. The hard parts: what goes where, what the browser may evict, and how queued writes reach the server.
What it is
Offline-first storage is a design choice: the app keeps its data on the device and draws the screen from that copy, whether or not the network is reachable. A request to the server becomes a background step that confirms what the local copy already holds or brings down changes it hasn't seen. A fetch-then-render page does the opposite. An app has two kinds of things to keep: the code and assets that let it boot, and the person's data. This page puts the first in the Cache API and the second in IndexedDB; both draw on the same storage budget the browser gives the origin, and the web.dev offline cookbook treats caching and request handling as separate decisions.
The shell (HTML, CSS, JavaScript, fonts) goes into the Cache API through a service worker. For an offline-first app the recommended default is cache first, falling back to the network, applied to most requests, with other patterns as exceptions. The worker's install event is where the static assets for this version go into the cache, and activate, which fires once the previous worker is out of the way, is where old caches are deleted and IndexedDB schema migrations run. Requests that aren't GET aren't cacheable, so a POST made offline needs a different path; the one this page uses is a queue of pending writes.
The person's data goes into IndexedDB. It stores records as key-value pairs where the value can be a structured object and the key can be one of its properties; an index on any property gives fast lookup and sorted enumeration. Each read and write runs inside a transaction, which is what stops two tabs of the same app from trampling each other's changes. The API is mostly asynchronous: you request an operation and get an event when it finishes. Data is scoped to the origin (scheme, host and port), so a page on another origin can't read it. One caveat on durability: since Firefox 40, matching other browsers, a transaction's complete event fires after the OS has been asked to write, possibly before the bytes are on disk. That matters for a power cut in the next moments, not for a closed tab.
// The record and its outbox entry commit together, or not at all.
async function saveNote(db: IDBDatabase, note: Note) {
const tx = db.transaction(['notes', 'outbox'], 'readwrite');
tx.objectStore('notes').put(note);
tx.objectStore('outbox').add({
key: crypto.randomUUID(), // idempotency key, reused on each retry
method: 'PUT',
url: `/api/notes/${note.id}`,
body: JSON.stringify(note),
at: Date.now(),
});
await whenComplete(tx);
void flush(db); // try now; a failed request leaves the entry in place
}
function whenComplete(tx: IDBTransaction) {
return new Promise<void>((resolve, reject) => {
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
tx.onabort = () => reject(tx.error);
});
}
async function flush(db: IDBDatabase) {
for (const entry of await readOutboxInOrder(db)) {
try {
const res = await fetch(entry.url, {
method: entry.method,
headers: { 'Idempotency-Key': entry.key, 'Content-Type': 'application/json' },
body: entry.body,
});
if (res.status === 409) { await markConflict(db, entry); continue; }
if (!res.ok) break; // any other failure: stop here, keep order
await removeFromOutbox(db, entry);
} catch {
break; // no network: try again on the next trigger
}
}
}When to use it
Use the pattern when the person has to keep working while the network is gone or flaky: field inspection tools, note taking, email, point of sale, travel. The Background Synchronization API's own example is an email client that lets someone compose and send with no connection: the page registers a sync with a tag, and the service worker receives a sync event when the network is available again and sends the mail. The API is limited to secure contexts and is not Baseline, because some widely used browsers lack it, so treat it as an extra trigger for the outbox rather than as the outbox.
Use it for read-heavy content where a stale copy is better than a spinner: articles, timelines, leaderboards. The caching patterns differ in what they trade. Network falling back to cache gives online users fresh content and offline users the older copy, but on a slow or flaky connection a person can wait a long time for a fallback they already have on the device. Cache then network shows the cached copy at once and updates the page when the network answers, at the cost of two requests and a UI that must take the update without jolting what the person is reading. Stale-while-revalidate serves the cache and refreshes it for next time, which suits things like avatars where the newest version isn't essential.
Plan for quota and eviction from the start. Storage is best-effort by default: it stays as long as the origin is under quota, the device has room and the person doesn't clear it. Under storage pressure the browser deletes the data of the least recently used origin, then the next, and an eviction removes all of an origin's data at once (IndexedDB and Cache API together) rather than part of it. navigator.storage.persist() asks to be skipped by that eviction; Firefox shows the person a prompt, while Chromium-based browsers and Safari grant or deny silently based on how much the person has used the site. navigator.storage.estimate() reports usage and quota as estimates, with cross-origin resources padded. Writes past the quota fail with QuotaExceededError, so wrap them in try/catch and free space before storing more.
| Browser or store | Limit | Note |
|---|---|---|
Web Storage (localStorage, sessionStorage) | 5 MiB each per origin, 10 MiB total | Throws |
Chrome and other Chromium browsers | Up to 60% of total disk per origin | Same in best-effort and persistent mode |
Firefox, best-effort | Smaller of 10% of disk or a 10 GiB group limit per site | Persistent origins get up to 50% of disk, capped at 8 TiB |
Safari on macOS 14 and iOS 17 or later | About 60% of disk per origin for browser apps, 15% for embedded web views | WebKit caps all origins together at 80% of disk for browser apps, 20% for embedded web views |
Safari with tracking prevention on | Script-written data deleted after seven days of browser use with no interaction | Server-set cookies are exempt |
Decide whether you're online from the request, not from a flag. navigator.onLine is false when the browser knows there is no network, but true can mean a LAN with no route to the internet, a virtual network adapter that reports itself connected, or on Windows the result of a reachability check that a firewall or VPN can block. MDN describes the property as unreliable and advises hints rather than disabled features. Our advice: let the online event trigger a flush, and let a successful response be what marks the app as connected.
When not to
Don't go offline-first when a write has to be refused by the server before the person sees it succeed, or when stale data is wrong the moment it's stale: payments, seat booking, inventory with hard limits, anything where a local success that later fails costs more than a disabled button. Show a clear offline state and hold the action. The same goes for requests with no offline meaning, such as analytics pings; pass them straight to the network with no cache involved.
Don't reach for IndexedDB to keep a few preferences. A theme choice or a dismissed banner fits localStorage: string keys and values, no expiry, scoped to the origin and the protocol, with the caveat that a private window clears it when the last private tab closes. Stay well under the 5 MiB cap and keep the values small.
Don't build it for a three-second blip. A retry with backoff on the failed request, plus the last response kept in memory, covers a dropped packet or a tunnel. The outbox, the schema migrations, conflict handling and eviction handling are a lot of surface for a gap the person barely notices; Reconnect and resume covers the lighter version.
Compared
| Store | Good at | Reach for it when | The simpler choice wins when |
|---|---|---|---|
localStorage | String key-values, no expiry, trivial API | A handful of flags and preferences | You need objects, indexes, transactions or more than a few megabytes: use IndexedDB |
IndexedDB | Structured records, indexes, transactions, request-and-event API | The person's data: records you query and edit offline | The data is a few strings (localStorage) or whole HTTP responses (Cache API) |
Cache API with a service worker | Request and response pairs; cache-first boot of the shell | The app's code, assets and GET responses | The request isn't GET: the Cache API won't hold it, so keep the pending write in another store, such as an IndexedDB outbox |
Memory in the page | No storage API to call, nothing to migrate or evict | Scratch state for one session, derived data | You need the data after the tab closes or reloads: pick one of the stores above |
Background Sync | A | Re-sending the outbox in browsers that have it | You need all browsers covered: flush on app start and on the |
In a picture
Step 1 of 3
Write locally, show at once
An edit goes into one IndexedDB transaction that touches two stores: the record itself and an outbox entry describing the request to send. The screen renders from the record as soon as the transaction completes.