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:
- Does the server need to read this data directly on incoming HTTP requests?
- Are you storing a few small primitives or a large, structured dataset?
- Is the payload an HTTP response, an internal application file, or a file on the user's disk?
- Can the application recover gracefully if the browser evicts the data under storage pressure?
At a Glance
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:
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,
sessionStorageis 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
Because document.cookie exposes a raw string interface, manual parsing is error-prone. Use a small helper that handles URL decoding safely:
Key Cookie Attributes
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:
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
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:
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():
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
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):
To prevent open tabs from blocking future schema upgrades, always listen for onversionchange and close the connection promptly:
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:
Querying via Indexes
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
keyPathand secondary indexes upfront based on your query patterns. - Close connections on
versionchangeso new deployments can migrate smoothly. - Handle
QuotaExceededError,AbortError, andVersionError. - 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
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:
Service Worker Caching Lifecycle
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
Reading and Writing Files in OPFS
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):
Saving Changes to Disk
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:
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
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
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:
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
Most production web applications combine several APIs, assigning each a single responsibility:
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:
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(orStrict) cookies for session identifiers. - Enforce a strong Content Security Policy (CSP), strict output encoding, and dependency auditing—switching from
localStorageto 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:
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/Responsepairs? 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
QuotaExceededErroris 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
- IndexedDB API — MDN
- Cache API — MDN
- File System API and Origin Private File System (OPFS) — MDN
- File System Access API — MDN
- Storage API (
StorageManager) — MDN - Storage Quotas and Eviction Criteria — MDN
- Web Storage — WHATWG HTML Living Standard
- Storage Buckets API — WICG Draft Specification