> 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.

# 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

| API                                        | Data Model                                                     | Persistence                                                      | Execution                                                                   | Best For                                                                        |
| ------------------------------------------ | -------------------------------------------------------------- | ---------------------------------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| **Cookies**                                | Small name-value pairs with HTTP attributes                    | Session or persistent (with expiration)                          | `document.cookie` is sync; attached automatically to matching HTTP requests | Server-readable session state on every request                                  |
| **`localStorage`**                         | String-only key-value pairs                                    | Persists across browser restarts                                 | **Synchronous**                                                             | Small UI preferences or client settings                                         |
| **`sessionStorage`**                       | String-only key-value pairs                                    | Scoped to a single tab/top-level browsing session                | **Synchronous**                                                             | Ephemeral per-tab state (e.g., multi-step form drafts)                          |
| **IndexedDB**                              | Object stores, keys, indexes, transactions                     | Origin-scoped; subject to quota & eviction                       | **Asynchronous**                                                            | Structured records, offline datasets, Blobs/Files                               |
| **Cache Storage**                          | `Request` / `Response` pairs                                   | Origin-scoped; subject to quota & eviction                       | **Asynchronous**                                                            | Offline app shells and HTTP response caching in Service Workers                 |
| **OPFS**                                   | Origin-private files and directories                           | Origin-scoped; subject to quota & eviction                       | Async on main thread; sync handles in Web Workers                           | Large internal files, SQLite/WASM databases, media processing                   |
| **File System Access API**                 | User-selected files and directories on the host OS             | File handles can be persisted in IndexedDB (requires permission) | **Asynchronous**                                                            | Local file editors, IDE tools, and document workflows                           |
| **`StorageManager`** (`navigator.storage`) | Metadata & lifecycle API (does not store data itself)          | —                                                                | **Asynchronous**                                                            | Inspecting storage quota and requesting persistent storage                      |
| **Storage Buckets**                        | Isolated groups of storage endpoints with independent policies | Draft / experimental                                             | **Asynchronous**                                                            | Separating 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:

```text
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`

```javascript
// 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:

```javascript
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"
```

### Key Cookie Attributes

| Attribute                    | Purpose                                                                                                                      |
| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `Max-Age` / `Expires`        | Sets a persistent lifetime. Omitting both creates a session cookie that expires when the browser session ends.               |
| `Path`                       | Restricts the URL path prefix that triggers the browser to send the cookie.                                                  |
| `Domain`                     | Widens scope to include subdomains when set. Omit `Domain` for host-only cookies unless cross-subdomain sharing is required. |
| `Secure`                     | Transmits the cookie only over HTTPS connections. Always enable in production.                                               |
| `HttpOnly`                   | Hides the cookie from client-side JavaScript (`document.cookie`), restricting access to HTTP requests.                       |
| `SameSite=Lax\|Strict\|None` | Controls whether the cookie is sent on cross-site requests. `SameSite=None` requires `Secure`.                               |
| `Partitioned`                | Opts third-party cookies into CHIPS (Cookies Having Independent Partitioned State), keying them by top-level site.           |

:::note\[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:

```javascript
// 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

```javascript
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:

```javascript
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()`:

```javascript
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

```text
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):

```javascript
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:

```javascript
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:

```javascript
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

```javascript
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));
}
```

:::tip\[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

```javascript
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:

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

const articles = await networkResponse.json();
```

### Service Worker Caching Lifecycle

```javascript title="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

| Dimension                              | Origin 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?** | No                                                     | Yes (explicit file picker & permission prompt)         |
| **Primary use case**                   | Internal app files, SQLite/WASM storage, media buffers | Opening and saving user-owned local documents          |
| **Entry point**                        | `navigator.storage.getDirectory()`                     | `window.showOpenFilePicker()` / `showSaveFilePicker()` |

### Reading and Writing Files in OPFS

```javascript
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):

```javascript
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

```javascript
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:

```javascript
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

```javascript
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

```javascript
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:

```javascript
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

| Requirement                                         | Recommended API                                | Why                                                           |
| --------------------------------------------------- | ---------------------------------------------- | ------------------------------------------------------------- |
| Server needs session state on every HTTP request    | **Cookies** (`HttpOnly`, `Secure`, `SameSite`) | Sent automatically by the browser in HTTP headers             |
| Theme, locale, or a few small UI flags              | **`localStorage`**                             | Zero setup; tiny synchronous payloads                         |
| Multi-step wizard state isolated to one tab         | **`sessionStorage`**                           | Automatically scoped to the tab's lifetime                    |
| Structured records, search indexes, offline queues  | **IndexedDB**                                  | Async transactions, secondary indexes, Blob support           |
| Offline app shell and cached HTTP responses         | **Cache Storage**                              | Native `Request` / `Response` matching for Service Workers    |
| Large internal files or client-side SQLite/WASM     | **OPFS**                                       | High-throughput file I/O with sync Worker handles             |
| Opening and editing files on the user's computer    | **File System Access API**                     | Native OS file picker and direct disk write streams           |
| Monitoring available disk quota and eviction status | **`navigator.storage`**                        | Standard `estimate()`, `persisted()`, and `persist()` methods |

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

```text
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:

```javascript
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:

```javascript
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

- [Web Storage API — MDN](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API)
- [IndexedDB API — MDN](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API)
- [Cache API — MDN](https://developer.mozilla.org/en-US/docs/Web/API/Cache)
- [File System API and Origin Private File System (OPFS) — MDN](https://developer.mozilla.org/en-US/docs/Web/API/File_System_API)
- [File System Access API — MDN](https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API)
- [Storage API (`StorageManager`) — MDN](https://developer.mozilla.org/en-US/docs/Web/API/Storage_API)
- [Storage Quotas and Eviction Criteria — MDN](https://developer.mozilla.org/en-US/docs/Web/API/Storage_API/Storage_quotas_and_eviction_criteria)
- [Web Storage — WHATWG HTML Living Standard](https://html.spec.whatwg.org/multipage/webstorage.html)
- [Storage Buckets API — WICG Draft Specification](https://wicg.github.io/storage-buckets/)
