For AI agents: the complete documentation index is available at https://nhanbe.id.vn/llms.txt, the full documentation bundle is available at https://nhanbe.id.vn/llms-full.txt, and this page is available as Markdown at https://nhanbe.id.vn/building-for-the-web/web-api/standard-api.md.

Browser Storage APIs

Compare standard browser storage APIs—Cookies, localStorage, sessionStorage, IndexedDB, Cache Storage, OPFS, and the File System Access API—by data model, lifecycle, quota, and use case.

Browser Storage APIs

Browser storage is not a single monolithic store. Each storage mechanism has its own data model, lifecycle, relationship with HTTP, and performance cost. When choosing a storage API, start not with "Which API is easiest to call?", but with four architectural questions:

  1. Does the server need to read this data directly on incoming HTTP requests?
  2. Are you storing a few small primitives or a large, structured dataset?
  3. Is the payload an HTTP response, an internal application file, or a file on the user's disk?
  4. Can the application recover gracefully if the browser evicts the data under storage pressure?

At a Glance

APIData ModelPersistenceExecutionBest For
CookiesSmall name-value pairs with HTTP attributesSession or persistent (with expiration)document.cookie is sync; attached automatically to matching HTTP requestsServer-readable session state on every request
localStorageString-only key-value pairsPersists across browser restartsSynchronousSmall UI preferences or client settings
sessionStorageString-only key-value pairsScoped to a single tab/top-level browsing sessionSynchronousEphemeral per-tab state (e.g., multi-step form drafts)
IndexedDBObject stores, keys, indexes, transactionsOrigin-scoped; subject to quota & evictionAsynchronousStructured records, offline datasets, Blobs/Files
Cache StorageRequest / Response pairsOrigin-scoped; subject to quota & evictionAsynchronousOffline app shells and HTTP response caching in Service Workers
OPFSOrigin-private files and directoriesOrigin-scoped; subject to quota & evictionAsync on main thread; sync handles in Web WorkersLarge internal files, SQLite/WASM databases, media processing
File System Access APIUser-selected files and directories on the host OSFile handles can be persisted in IndexedDB (requires permission)AsynchronousLocal file editors, IDE tools, and document workflows
StorageManager (navigator.storage)Metadata & lifecycle API (does not store data itself)—AsynchronousInspecting storage quota and requesting persistent storage
Storage BucketsIsolated groups of storage endpoints with independent policiesDraft / experimentalAsynchronousSeparating critical drafts from disposable caches (check browser support first)

localStorage, IndexedDB, Cache Storage, and the Origin Private File System (OPFS) all share the browser's origin storage quota. Because browsers manage a shared pool and can evict non-persistent data when disk space runs low, a successful write never guarantees permanent durability.

Origins, Partitioning, and Lifecycle

The Origin Boundary

An origin is defined by the tuple of scheme + host + port. For example, the following three URLs belong to three distinct origins:

https://example.com
http://example.com
https://example.com:8443

localStorage, sessionStorage, IndexedDB, Cache Storage, and OPFS are strictly isolated by the same-origin policy. JavaScript running on https://app.example.com cannot directly read IndexedDB stores belonging to https://api.example.com.

Cookies follow a different scoping model: the Domain, Path, and SameSite attributes determine which HTTP requests carry a cookie. That is why cookies are fundamentally an HTTP state mechanism rather than a general-purpose client key-value store.

Session Scope, Persistence, and Eviction

  • Session scope: Data is discarded when the browsing context ends (for example, sessionStorage is cleared when the tab closes).
  • Best-effort persistence: Data survives browser restarts, but the user can clear site data at any time, and the browser can evict the origin's storage under disk pressure.
  • Eviction: When device storage runs low, the browser purges non-persistent origin data—typically on a least-recently-used (LRU) basis—in an all-or-nothing pass per origin (or per storage bucket).
  • User-initiated clearing: Clearing site data wipes all origin storage regardless of which API wrote it.

Never treat browser storage as the sole source of truth for irreplaceable data. Critical user work should be synced to a backend or offer an explicit export flow.


1. Cookies

Cookies bridge state between the browser and the server. The browser automatically attaches matching cookies via the Cookie request header, and servers create or update them via the Set-Cookie response header.

When to Use Cookies

Use cookies when the server needs state attached to incoming HTTP requests:

  • Session identifiers
  • Refresh tokens or authentication credentials backed by an appropriate security policy
  • Server-rendered preferences (such as theme or locale needed during SSR to prevent a flash of unstyled content)
  • Privacy-compliant attribution state

Do not use cookies as a client-side database. Because matching cookies are transmitted on every HTTP request, stuffing kilobytes of data into cookies inflates request headers and degrades network performance.

Reading and Writing via document.cookie

// Read: returns a semicolon-delimited string of all non-HttpOnly cookies
console.log(document.cookie);

// Write: each assignment creates or updates a single cookie
document.cookie = [
  `theme=${encodeURIComponent("dark")}`,
  "Max-Age=2592000", // 30 days in seconds
  "Path=/",
  "SameSite=Lax",
  "Secure",
].join("; ");

// Delete: overwrite the same cookie name, Path, and Domain with Max-Age=0
document.cookie = "theme=; Max-Age=0; Path=/; SameSite=Lax; Secure";

Because document.cookie exposes a raw string interface, manual parsing is error-prone. Use a small helper that handles URL decoding safely:

function getCookie(name) {
  const prefix = `${encodeURIComponent(name)}=`;
  const match = document.cookie
    .split("; ")
    .find((entry) => entry.startsWith(prefix));

  return match ? decodeURIComponent(match.slice(prefix.length)) : null;
}

console.log(getCookie("theme")); // "dark"
AttributePurpose
Max-Age / ExpiresSets a persistent lifetime. Omitting both creates a session cookie that expires when the browser session ends.
PathRestricts the URL path prefix that triggers the browser to send the cookie.
DomainWidens scope to include subdomains when set. Omit Domain for host-only cookies unless cross-subdomain sharing is required.
SecureTransmits the cookie only over HTTPS connections. Always enable in production.
HttpOnlyHides the cookie from client-side JavaScript (document.cookie), restricting access to HTTP requests.
SameSite=Lax|Strict|NoneControls whether the cookie is sent on cross-site requests. SameSite=None requires Secure.
PartitionedOpts third-party cookies into CHIPS (Cookies Having Independent Partitioned State), keying them by top-level site.
[HttpOnly and CSRF]

Marking a cookie HttpOnly prevents XSS payloads from reading the raw cookie value via document.cookie, but it does not prevent Cross-Site Request Forgery (CSRF)—nor does it stop an XSS script from firing authenticated fetch() requests from the same origin. Pair HttpOnly with SameSite, CSRF tokens, and server-side Origin verification.

Cookies and fetch()

Same-origin fetch() requests send cookies by default (credentials: "same-origin"). Cross-origin requests require credentials: "include" on the client and an explicit Access-Control-Allow-Credentials: true header (with a non-wildcard origin) from the server:

// Same-origin request (default behavior)
const meResponse = await fetch("/api/me", {
  credentials: "same-origin",
});

// Cross-origin authenticated request
const externalResponse = await fetch("https://api.example.test/me", {
  credentials: "include",
});

Setting credentials: "include" does not bypass SameSite rules, third-party cookie blocking, or CORS policies—it simply instructs Fetch to participate in the credentialed request flow when browser policies allow it.


2. Web Storage API (localStorage & sessionStorage)

The Web Storage API provides two string-only key-value stores:

  • localStorage: Shared across all tabs and windows of the same origin; persists across browser restarts.
  • sessionStorage: Isolated to the origin and the current browser tab (top-level browsing context); cleared when the tab closes.

Both APIs are synchronous and store only strings. Objects must be serialized (typically with JSON.stringify()) before writing and parsed back on read.

Basic Storage Methods

const storage = window.localStorage;

storage.setItem("theme", "dark");
const theme = storage.getItem("theme"); // "dark" | null

storage.removeItem("theme");
console.log(storage.length);
console.log(storage.key(0)); // key name at index 0, or null

// Warning: wipes every key stored under this origin
// storage.clear();

Storing Structured Objects Safely

Always version your storage keys and wrap reads and writes in try / catch. JSON.parse() can throw on corrupted values, and localStorage access itself can throw SecurityError or QuotaExceededError in strict privacy modes:

const SETTINGS_KEY = "app:settings:v1";

const defaultSettings = {
  theme: "light",
  compactMode: false,
};

function saveSettings(settings) {
  try {
    localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
  } catch (error) {
    console.warn("Unable to persist settings:", error);
  }
}

function readSettings() {
  try {
    const raw = localStorage.getItem(SETTINGS_KEY);
    return raw ? { ...defaultSettings, ...JSON.parse(raw) } : defaultSettings;
  } catch {
    // Handle malformed JSON or blocked storage gracefully
    return defaultSettings;
  }
}

Synchronizing State Across Tabs

The storage event fires on other open documents sharing the same origin when localStorage changes—it does not fire in the tab that called setItem():

window.addEventListener("storage", (event) => {
  if (event.storageArea !== localStorage) return;
  if (event.key !== SETTINGS_KEY) return;

  const nextSettings = event.newValue
    ? JSON.parse(event.newValue)
    : defaultSettings;

  applySettings(nextSettings);
});

If you need structured, bi-directional messaging between tabs without writing to disk, use the BroadcastChannel API instead.

When Not to Use Web Storage

Avoid localStorage and sessionStorage for:

  • Large datasets or collections that require filtering, sorting, or indexing
  • Binary data (Blob, ArrayBuffer, images)
  • Frequent high-throughput writes (synchronous serialization blocks the main thread and hurts INP)
  • Sensitive secrets or raw authentication tokens
  • Multi-step updates that require atomic transactions

3. IndexedDB

IndexedDB is a transactional, asynchronous object database built into the browser. It stores structured JavaScript objects directly via the structured clone algorithm (including Date, Set, Map, Blob, and File instances) and supports secondary indexes for fast queries. It is the standard choice for offline-capable web applications.

Conceptual Hierarchy

Database (e.g., "notes-app", version 1)
└── Object Store ("notes", keyPath: "id")
    ├── Record: { id: "note-1", title: "...", body: "...", updatedAt: 1730000000000 }
    └── Index: "byUpdatedAt" (on field "updatedAt")

Schema changes happen exclusively inside the onupgradeneeded event handler, which runs whenever you pass a higher version integer to indexedDB.open(name, version).

Opening a Database and Migrating the Schema

Because the native IndexedDB API uses DOM request events rather than Promises, wrap IDBRequest and IDBTransaction in small Promise helpers (or use a lightweight library like idb in production):

function requestToPromise(request) {
  return new Promise((resolve, reject) => {
    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
  });
}

function openNotesDb() {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open("notes-app", 1);

    request.onupgradeneeded = () => {
      const db = request.result;
      if (!db.objectStoreNames.contains("notes")) {
        const store = db.createObjectStore("notes", { keyPath: "id" });
        store.createIndex("byUpdatedAt", "updatedAt");
      }
    };

    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);

    // Fired if another open tab holds an older version connection open
    request.onblocked = () => {
      console.warn("Close other open tabs to complete the database upgrade.");
    };
  });
}

To prevent open tabs from blocking future schema upgrades, always listen for onversionchange and close the connection promptly:

const db = await openNotesDb();

db.onversionchange = () => {
  db.close();
  console.info("A newer database version is available. Please reload this tab.");
};

Reading, Writing, and Deleting Records

Always await the transaction lifecycle (oncomplete, onerror, onabort) rather than just individual write requests so you know the transaction committed to disk:

function transactionToPromise(tx) {
  return new Promise((resolve, reject) => {
    tx.oncomplete = () => resolve();
    tx.onerror = () => reject(tx.error);
    tx.onabort = () => reject(tx.error ?? new Error("IndexedDB transaction aborted"));
  });
}

async function saveNote(note) {
  const db = await openNotesDb();
  const tx = db.transaction("notes", "readwrite");
  const committed = transactionToPromise(tx);

  tx.objectStore("notes").put(note);
  await committed;
}

async function readNote(id) {
  const db = await openNotesDb();
  const tx = db.transaction("notes", "readonly");
  return requestToPromise(tx.objectStore("notes").get(id));
}

await saveNote({
  id: "note-1",
  title: "Browser storage notes",
  body: "IndexedDB runs asynchronously and supports transactions.",
  updatedAt: Date.now(),
});

console.log(await readNote("note-1"));

Querying via Indexes

async function listNotesByUpdatedAt(minTimestamp = 0) {
  const db = await openNotesDb();
  const tx = db.transaction("notes", "readonly");
  const index = tx.objectStore("notes").index("byUpdatedAt");
  const range = IDBKeyRange.lowerBound(minTimestamp);

  return requestToPromise(index.getAll(range));
}
[Keep Transactions Short-Lived]

IndexedDB transactions auto-commit as soon as the event loop turns without any pending database requests. Never await fetch(...) in the middle of an open IndexedDB transaction—the transaction will become inactive and throw TransactionInactiveError on your next write. Fetch network data first, then open the transaction to write the result.

IndexedDB Implementation Checklist

  • Run all schema creation and migrations inside onupgradeneeded.
  • Define your keyPath and secondary indexes upfront based on your query patterns.
  • Close connections on versionchange so new deployments can migrate smoothly.
  • Handle QuotaExceededError, AbortError, and VersionError.
  • Remember that IndexedDB has the same XSS exposure as localStorage—any script running on the origin can read every object store.

4. Cache API / Cache Storage

The Cache Storage API stores HTTP Request / Response pairs. While designed primarily for Service Workers and Progressive Web Apps (PWAs), it is also accessible from the main window thread via caches.

Basic Cache Operations

const cache = await caches.open("app-static-v1");

// Fetch and cache multiple URLs atomically
await cache.addAll([
  "/",
  "/index.html",
  "/styles.css",
  "/app.js",
]);

// Look up a cached response
const cachedResponse = await cache.match("/app.js");
if (cachedResponse) {
  console.log(await cachedResponse.text());
}

// Remove an obsolete entry
await cache.delete("/old-bundle.js");

Because a Response body stream can only be consumed once, call response.clone() whenever you need to both cache a response and read its body in your application code:

const networkResponse = await fetch("/api/articles");
await cache.put("/api/articles", networkResponse.clone());

const articles = await networkResponse.json();

Service Worker Caching Lifecycle

sw.js
const CACHE_NAME = "app-shell-v2";
const APP_SHELL = ["/", "/index.html", "/styles.css", "/app.js"];

self.addEventListener("install", (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => cache.addAll(APP_SHELL)),
  );
});

self.addEventListener("fetch", (event) => {
  if (event.request.method !== "GET") return;

  event.respondWith(
    caches.match(event.request).then((cached) => cached ?? fetch(event.request)),
  );
});

self.addEventListener("activate", (event) => {
  event.waitUntil(
    caches.keys().then((keys) =>
      Promise.all(
        keys
          .filter((key) => key !== CACHE_NAME)
          .map((key) => caches.delete(key)),
      ),
    ),
  );
});

In production Service Workers, pair each route type with an intentional caching strategy:

  • Hashed static assets & app shell: Precache or Cache-First.
  • Frequently updated API GET endpoints: Network-First or Stale-While-Revalidate.
  • Authenticated or sensitive responses: Do not cache, or clear caches explicitly on sign-out.
  • Mutating requests (POST, PUT, DELETE): Do not store in Cache Storage; queue offline mutations in IndexedDB instead.

Always bump CACHE_NAME and purge outdated caches inside the activate event so users are never stuck running stale assets.


5. Origin Private File System (OPFS)

The Origin Private File System (OPFS) provides a sandboxed virtual file system private to the origin. Files stored in OPFS are invisible to the user's OS file manager (Finder / Explorer), require no permission prompts, and are optimized for high-performance byte-level I/O.

OPFS vs. File System Access API

DimensionOrigin Private File System (OPFS)File System Access API
Visible in OS file explorer?No (hidden browser-managed storage)Yes (real files on the user's disk)
Requires user picker / permission?NoYes (explicit file picker & permission prompt)
Primary use caseInternal app files, SQLite/WASM storage, media buffersOpening and saving user-owned local documents
Entry pointnavigator.storage.getDirectory()window.showOpenFilePicker() / showSaveFilePicker()

Reading and Writing Files in OPFS

async function writeOpfsText(fileName, content) {
  const root = await navigator.storage.getDirectory();
  const draftsDir = await root.getDirectoryHandle("drafts", { create: true });
  const fileHandle = await draftsDir.getFileHandle(fileName, { create: true });

  const writable = await fileHandle.createWritable();
  await writable.write(content);
  await writable.close();
}

async function readOpfsText(fileName) {
  const root = await navigator.storage.getDirectory();
  const draftsDir = await root.getDirectoryHandle("drafts");
  const fileHandle = await draftsDir.getFileHandle(fileName);
  const file = await fileHandle.getFile();

  return file.text();
}

await writeOpfsText("draft-01.md", "# Offline Draft\nSaved in OPFS.");
console.log(await readOpfsText("draft-01.md"));

For performance-critical workloads like running SQLite compiled to WebAssembly (sqlite-wasm) or video editing, OPFS exposes createSyncAccessHandle() inside dedicated Web Workers, giving you synchronous, in-place file reads and writes without blocking the main UI thread.


6. File System Access API

The File System Access API lets web applications read and write real files and directories on the user's local machine after the user selects them via a native file picker. Because browser support is primarily Chromium-based, always feature-detect and provide an <input type="file"> / <a download> fallback.

Opening a Local File

File pickers must be triggered by a transient user activation (such as a button click event):

async function openTextFile() {
  if (!("showOpenFilePicker" in window)) {
    throw new Error("File System Access API is not supported in this browser.");
  }

  const [handle] = await window.showOpenFilePicker({
    types: [
      {
        description: "Markdown and text files",
        accept: { "text/plain": [".txt", ".md"] },
      },
    ],
    multiple: false,
  });

  const file = await handle.getFile();
  return {
    handle,
    name: file.name,
    text: await file.text(),
  };
}

Saving Changes to Disk

async function saveAsTextFile(content) {
  const handle = await window.showSaveFilePicker({
    suggestedName: "notes.txt",
    types: [
      {
        description: "Plain text file",
        accept: { "text/plain": [".txt"] },
      },
    ],
  });

  const writable = await handle.createWritable();
  await writable.write(content);
  await writable.close();
}

You can serialize a FileSystemFileHandle into IndexedDB so the user can reopen recent files across sessions. When restoring a saved handle, verify and re-request permission inside a user gesture:

async function verifyReadWritePermission(handle) {
  const options = { mode: "readwrite" };
  if ((await handle.queryPermission(options)) === "granted") {
    return true;
  }
  return (await handle.requestPermission(options)) === "granted";
}

Always handle AbortError gracefully in case the user dismisses the file picker dialog.


7. Storage API & StorageManager

navigator.storage does not store data directly; it exposes quota diagnostics and persistence controls for the origin's storage bucket.

Estimating Usage and Quota

const estimate = await navigator.storage.estimate();

console.log({
  usageBytes: estimate.usage,
  quotaBytes: estimate.quota,
  usagePercent:
    estimate.usage && estimate.quota
      ? ((estimate.usage / estimate.quota) * 100).toFixed(2) + "%"
      : null,
});

Treat usage and quota as approximations, not exact byte counts. Browsers intentionally pad or round quota figures to mitigate cross-site fingerprinting, and private browsing modes often report a reduced quota cap.

Requesting Persistent Storage

async function ensurePersistentStorage() {
  if (!navigator.storage?.persist) return false;

  const isPersisted = await navigator.storage.persisted();
  if (isPersisted) return true;

  return navigator.storage.persist();
}

Calling navigator.storage.persist() asks the browser to exempt the origin from automatic storage eviction under disk pressure. Browsers grant or deny this automatically (or prompt the user) based on heuristics such as whether the site is installed as a PWA, bookmarked, or receives push notifications. Even when granted, users can still clear site data manually.


8. Storage Buckets API (Experimental)

By default, when a browser evicts an origin's data, it wipes all storage APIs for that origin together. The Storage Buckets API proposes allowing an origin to partition its data into named buckets with independent eviction priorities, quotas, and expiration policies (for example, keeping a drafts bucket persistent while letting an attachments-cache bucket be evicted first).

Because this specification is still experimental and not supported across all major browser engines, always feature-detect before use:

if ("storageBuckets" in navigator) {
  const draftsBucket = await navigator.storageBuckets.open("drafts", {
    persisted: true,
  });

  const idb = draftsBucket.indexedDB;
  console.log(await draftsBucket.estimate());
}

Do not rely on Storage Buckets for core production data flows without verifying your target browser matrix and providing a standard origin-level fallback.


Choosing the Right Storage API

RequirementRecommended APIWhy
Server needs session state on every HTTP requestCookies (HttpOnly, Secure, SameSite)Sent automatically by the browser in HTTP headers
Theme, locale, or a few small UI flagslocalStorageZero setup; tiny synchronous payloads
Multi-step wizard state isolated to one tabsessionStorageAutomatically scoped to the tab's lifetime
Structured records, search indexes, offline queuesIndexedDBAsync transactions, secondary indexes, Blob support
Offline app shell and cached HTTP responsesCache StorageNative Request / Response matching for Service Workers
Large internal files or client-side SQLite/WASMOPFSHigh-throughput file I/O with sync Worker handles
Opening and editing files on the user's computerFile System Access APINative OS file picker and direct disk write streams
Monitoring available disk quota and eviction statusnavigator.storageStandard estimate(), persisted(), and persist() methods

Most production web applications combine several APIs, assigning each a single responsibility:

Cookies         -> Server-side session & authentication state
localStorage    -> Lightweight UI preferences (theme, sidebar collapsed state)
IndexedDB       -> Application records, offline drafts, mutation sync queue
Cache Storage   -> Static app shell bundles and cached GET API responses
OPFS            -> Large binary attachments, local SQLite database files
StorageManager  -> Quota health monitoring and persistence requests

Avoid duplicating the same state across multiple stores. When you must cache server state locally, define a single source of truth and explicit invalidation rules so your UI never renders conflicting snapshots.

Reusable JSON Wrapper for Web Storage

For small key-value preferences, a thin wrapper standardizes JSON serialization, fallback defaults, and quota error handling:

function createJsonStorage(storage) {
  return {
    read(key, fallback) {
      try {
        const raw = storage.getItem(key);
        return raw === null ? fallback : JSON.parse(raw);
      } catch {
        return fallback;
      }
    },

    write(key, value) {
      try {
        storage.setItem(key, JSON.stringify(value));
        return true;
      } catch (error) {
        if (error?.name === "QuotaExceededError") {
          console.warn("Web Storage quota exceeded for key:", key);
        }
        return false;
      }
    },

    remove(key) {
      try {
        storage.removeItem(key);
      } catch {
        // Ignore errors when storage is disabled or blocked
      }
    },
  };
}

const preferences = createJsonStorage(window.localStorage);
preferences.write("app:preferences:v1", { theme: "dark", compactMode: true });

Keep this helper strictly for lightweight settings—never use synchronous localStorage wrappers as a stand-in for IndexedDB.

Security and Privacy Guidelines

Never Store Raw Secrets in Client-Accessible Storage

Any JavaScript executing on your origin—including third-party analytics scripts or an injected XSS payload—can read localStorage, sessionStorage, IndexedDB, Cache Storage, and OPFS in full.

  • Never store plaintext passwords or long-lived secret keys in browser storage.
  • Prefer HttpOnly; Secure; SameSite=Lax (or Strict) cookies for session identifiers.
  • Enforce a strong Content Security Policy (CSP), strict output encoding, and dependency auditing—switching from localStorage to IndexedDB does not hide tokens from XSS.

Validate Data Read Back from Storage

Treat client storage as untrusted input. Users, browser extensions, or older releases of your own application can mutate stored values into unexpected shapes. Validate schemas before using stored data:

function isValidSettings(value) {
  return (
    typeof value === "object" &&
    value !== null &&
    (value.theme === "light" || value.theme === "dark") &&
    typeof value.compactMode === "boolean"
  );
}

Third-Party Contexts and Private Browsing

Modern browsers partition storage in third-party <iframe> embeds by top-level site to prevent cross-site tracking, and some privacy configurations block third-party storage altogether. Similarly, private/incognito windows often enforce lower quota ceilings and wipe all storage as soon as the last private tab closes. Always test storage flows in private windows and cross-origin embeds if your product supports them.

Storage Architecture Checklist

  • Server visibility: Does the server need this data on HTTP requests? Use cookies or explicit request headers.
  • Payload size & structure: Is it a tiny preference (localStorage) or a queryable dataset/binary payload (IndexedDB / OPFS)?
  • Offline HTTP caching: Are you caching network Request/Response pairs? Use Cache Storage.
  • File visibility: Is it an internal sandboxed file (OPFS) or a user-visible file on disk (File System Access API)?
  • Error & quota resilience: Does the app degrade gracefully when storage is blocked, permissions are denied, or QuotaExceededError is thrown?
  • Schema versioning: Are keys and IndexedDB schemas versioned with a clear migration path?
  • Runtime validation: Do you validate data shapes after reading from storage?
  • Eviction recovery: Does the application still work—and avoid data loss via backend sync or export—if the browser clears all site data?

References