Every web application stores something in the browser, and the most common front-end security question, where should the token go, has no safe answer inside the browser itself. localStorage, sessionStorage, IndexedDB, the Cache API and cookies differ in scope, lifetime and who can read them, but code running in your origin can read or abuse all of them. This guide explains how each browser storage mechanism actually behaves, who can read it (cross-site scripting, browser extensions, infostealers and other apps on the same origin), how to choose storage for session cookies, access tokens, refresh tokens and keys, how to clear it reliably at logout, and how to test and monitor it. It complements the OAuth for Browser-Based Applications and the BFF Pattern Guide, which covers the architecture decision; this page is about the storage mechanics. It is for front-end leads, application security engineers and reviewers of single-page applications (SPAs).
Key takeaways
- No browser storage is safe from your own origin's JavaScript. The OWASP HTML5 Security Cheat Sheet notes that XSS can read and write everything in Web Storage and IndexedDB; HttpOnly cookies are the only token store script cannot read.
- Keep tokens out of the browser when you can. RFC 10017 (a Best Current Practice published in August 2026) recommends against browser-based OAuth clients for sensitive applications; a backend-for-frontend with a
__Host-HttpOnly session cookie is the default for anything handling personal data. - If an SPA must hold tokens, minimise and bind them. Short-lived access tokens in memory, rotated refresh tokens, and DPoP (RFC 9449) with a non-extractable WebCrypto key turn stolen tokens into useless strings, though they cannot stop an attacker who runs code while the user is online.
- Storage is shared across the whole origin. There are no path restrictions, so two apps on one origin share localStorage and IndexedDB; isolate applications on separate hosts.
- Logout must clear the browser, not just the server. Send
Clear-Site-Dataand clear client state in code as well, as ASVS 5.0 V14.3.1 requires.
The browser storage mechanisms compared
MDN groups browser storage into cookies, Web Storage (localStorage and sessionStorage), IndexedDB, the Cache API and the Origin Private File System (OPFS). Their security properties differ more than their APIs suggest.
| Mechanism | Scope | Lifetime | Readable by page script | Sent to server automatically | Typical capacity |
|---|---|---|---|---|---|
| HttpOnly cookie | Host or domain and path, per attributes | Session or Max-Age/Expires | No | Yes, subject to SameSite | Small (around 4 KB per cookie) |
| Script-readable cookie | As above | As above | Yes, via document.cookie | Yes | Small |
localStorage | Origin, all tabs | Until cleared or evicted | Yes, synchronously | No | 5 MiB per origin (MDN) |
sessionStorage | Origin, one tab | Until the tab closes | Yes | No | 5 MiB per origin (MDN) |
| IndexedDB | Origin, all tabs and workers | Until cleared or evicted | Yes, asynchronously, including from service workers | No | Large, quota-managed |
| Cache API | Origin | Until cleared or evicted | Yes | No | Large, quota-managed |
| JavaScript memory (closure, worker) | One page or worker | Until reload | Only by code in that context | No | Not applicable |
- Persistence is not guaranteed: storage is best-effort by default and evicted least recently used first under pressure, unless
navigator.storage.persist()is granted. Safari, with tracking prevention on, deletes script-created storage for an origin after seven days of browser use without user interaction, while server-set cookies are exempt. Never rely on IndexedDB as the only copy of a key or token you cannot recreate. - Eviction is all or nothing: when an origin is evicted, its IndexedDB and Cache API data go together, which can surprise designs that keep a key in one store and encrypted data in another.
- Partitioning: browsers increasingly key third-party storage by the top-level site. MDN's state partitioning guide describes Firefox double-keying localStorage, sessionStorage, IndexedDB, the Cache API and service workers by origin and top-level site. An identity widget or payment iframe embedded on two sites therefore sees two separate stores, and needs the Storage Access API (
document.requestStorageAccess) or a top-level redirect to reach its first-party cookies.
Who can read browser storage
Most token storage debates consider only XSS. In practice there are five readers to design against, and they reach different stores.
| Threat | HttpOnly cookie | Web Storage and IndexedDB | In-memory token | Non-extractable key (DPoP) |
|---|---|---|---|---|
| XSS or a compromised third-party script (ATT&CK T1059.007) | Cannot read, but can ride the session (requests from the page) | Read and exfiltrate | Readable by code in the same context, harder to find | Cannot export, but can sign proofs while the page is open |
| Malicious or hijacked browser extension (T1176.001) | Readable with cookie permissions | Readable via content scripts | Readable via page injection | Usable while the page is open |
| Infostealer malware on the device (T1555.003, T1539) | Copied from the profile on disk | Copied from the profile on disk | Not persisted | Key material not exportable through the API; on-disk protection depends on the browser |
| Another app on the same origin | Shared if path or domain overlap | Fully shared (no path scoping) | Isolated | Shared if stored in the same origin's IndexedDB |
| Someone with the unlocked device | Via developer tools | Via developer tools | While the tab is open | Usable while open |
RFC 10017 frames the XSS case as four escalating attacks: single-execution token theft, persistent token theft (a handler that keeps stealing refreshed tokens), acquisition of new tokens by running a silent authorisation flow in a hidden iframe, and proxying requests through the user's own browser. Storage choice only affects the first two. The third and fourth succeed whatever you store, which is why preventing script injection (Content Security Policy, Trusted Types, dependency control) matters more than where the token sits. See the Client-Side Security Guide and the Cross-Site Scripting (XSS) Prevention Guide.
Choosing storage for each kind of secret
| What you are storing | Recommended | Acceptable with conditions | Avoid |
|---|---|---|---|
| Session identifier (server-side session or BFF) | __Host- (or __Host-Http-) cookie, Secure, HttpOnly, SameSite=Lax or Strict, Path=/ | __Secure- cookie with a Domain when subdomains genuinely must share it | Any Web Storage; script-readable cookies |
| OAuth access token in an SPA | Memory only, minutes-long lifetime, DPoP-bound | sessionStorage to survive reloads, with short lifetime | localStorage; long-lived bearer tokens |
| OAuth refresh token in an SPA | Not in the browser (BFF or token-mediating backend) | Isolated in a Web Worker, rotated on every use, DPoP-bound, absolute lifetime | localStorage or IndexedDB with no binding |
| DPoP or other signing key | WebCrypto key generated with extractable: false, stored in IndexedDB | Regenerate per session if persistence is unreliable | Exportable keys; keys in JSON in Web Storage |
| ID token and user profile | Server-side, or minimal claims in memory | Non-sensitive display fields in sessionStorage | Full ID token or personal data in localStorage |
| Offline application data | IndexedDB or OPFS with only the data the feature needs | Encrypted with a key that requires user presence to unlock | Regulated personal data stored "temporarily" with no expiry |
Decision guidance: if the front end and API share a site and you control both, use plain cookie sessions; RFC 10017 section 7.1 recommends this over OAuth in the browser for single-domain applications. If the API is third-party or cross-site, use a backend-for-frontend; see the OAuth for Browser-Based Applications and the BFF Pattern Guide. Keep a pure browser-based OAuth client for low-sensitivity apps or where no backend is possible, and then apply every control in the SPA rows above. Small teams gain the most from avoiding token storage entirely, because the BFF moves the hard problems to server code they already know how to secure.
Making non-extractable keys and DPoP work
- Generate in the browser:
crypto.subtle.generateKey({name: "ECDSA", namedCurve: "P-256"}, false, ["sign"])creates a key pair whose private key cannot be read out throughexportKey()orwrapKey(). Store theCryptoKeyobject itself in IndexedDB, never a serialised form. - Bind tokens: with DPoP the authorisation server binds the access token to the key thumbprint (
cnf.jkt) and, for public clients, binds refresh tokens too, so tokens copied out of storage fail without a fresh proof. - Know the limit: RFC 9449 is explicit that code running in the client can still generate valid proofs while the victim is online, and can obtain a new grant bound to its own key. OWASP likewise warns that non-extractable keys do not fully protect persisted keys from someone with the browser profile. DPoP defeats offline replay of stolen tokens, not live compromise.
Cookies for sessions, done properly
For server sessions and BFFs the cookie is the token store, so its attributes are the controls. ASVS 5.0 V3.3.1, V3.3.3 and V3.3.4 require Secure, the __Host- prefix unless sharing is designed, and HttpOnly for values scripts do not need.
- Prefixes: the browser rejects a
__Host-cookie unless it isSecure, set over HTTPS, hasPath=/and noDomain, which pins it to one host and stops a sibling subdomain from overwriting it. The newer__Http-and__Host-Http-prefixes also requireHttpOnly, so the cookie cannot be set from JavaScript. Browsers without prefix support accept prefixed cookies anyway, so prefixes are defence in depth. - SameSite:
StrictorLaxfor session cookies;NonerequiresSecureand should be reserved for cookies that genuinely must flow in cross-site requests. Do not rely on the browser's Lax default, which some browsers relax to allow top-level POSTs within two minutes of the cookie being set. Keep CSRF protection in place; see the CSRF Prevention Guide. - Lifetime:
Max-Agetakes precedence overExpires. Use session cookies or shortMax-Ageplus a server-side absolute session limit, and rotate the session identifier at sign-in and privilege change (ASVS V7.2.4). - Partitioned cookies: an embedded widget that needs state in a third-party context can use
Partitioned(CHIPS), which requiresSecure; MDN recommends a__Host-prefix with it. - Path is not isolation: MDN states that
Pathis not intended as a security measure. Separate applications by host, not by path.
Beyond tokens: data that should never be in browser storage
ASVS 5.0 V14.3.3 requires that browser storage holds no sensitive data apart from session tokens. Teams regularly break this with convenience caches: full user profiles with dates of birth, API responses containing account numbers, draft form content, feature-flag payloads exposing internal endpoints, and analytics identifiers joined to email addresses.
- Minimise: cache identifiers and render data, not full records. Treat any value in storage as attacker-readable and attacker-writable.
- Validate on read: the OWASP cheat sheet warns that XSS can write malicious data into storage; data read back from localStorage or IndexedDB must be encoded and validated like network input, or stored XSS persists across sessions.
- Service workers and caches: a service worker that caches authenticated API responses in the Cache API keeps personal data on disk after logout. Exclude authenticated responses from caching, or clear the caches explicitly at logout.
- Isolation by host: put admin consoles, customer apps and marketing pages on different hosts so one vulnerable page cannot read another app's storage.
Clearing state at logout and session end
- Revoke server-side first: end the session or revoke the refresh token at the authorisation server so copies elsewhere stop working (ASVS V7.4.1). See the OAuth Token Introspection and Revocation Guide.
- Send Clear-Site-Data: on the logout response send
Clear-Site-Data: "cookies", "storage", "cache". The"storage"directive clears localStorage, sessionStorage, IndexedDB and service worker registrations;"cookies"applies to the registered domain, including subdomains, so check that it will not log users out of sibling apps unexpectedly. Values must be quoted and the header works only over HTTPS. - Clear in code too: ASVS V14.3.1 notes that the client must also be able to clean up when the server cannot be reached; call
localStorage.clear(), delete IndexedDB databases, delete Cache API entries and drop in-memory tokens, then notify other tabs (for example withBroadcastChannel) so they discard their copies. - Handle idle and absolute timeouts the same way as an explicit logout, not just by letting tokens expire.
Testing, detection and measurement
- Static checks: lint and code-review rules that flag
localStorage.setItemand IndexedDB writes with token-like keys (token,jwt,refresh,id_token). - Dynamic checks: an end-to-end test that signs in, inspects every storage area through the browser automation API, asserts that no JWT-shaped or high-entropy values are present, logs out and asserts that storage is empty. Run it in CI on every release.
- Header checks: scanners or synthetic tests that verify cookie prefixes,
HttpOnly,SameSite,Clear-Site-Dataon logout and a Content Security Policy with reporting (ASVS V3.4.3). - Server-side detection: refresh token reuse after rotation, the same session or token used from two networks or user agents, DPoP proofs with mismatched keys, and CSP violation reports that show injected script. These are the signals of the session hijacking described in the Session Hijacking and Cookie Theft Guide.
Metrics:
- Number of applications storing access or refresh tokens in localStorage or IndexedDB (target zero).
- Percentage of session cookies using the
__Host-prefix withHttpOnlyand an explicitSameSite. - Percentage of logout flows that pass the empty-storage test.
- Median and maximum access token lifetime issued to browser clients.
- Refresh token reuse detections per month, and time to revoke the token family.
Moving an existing SPA off localStorage
- Inventory every value written to browser storage, with owner and purpose.
- Remove sensitive data that is not a token, and move render caches to
sessionStorageor memory. - Shorten access token lifetime and enable refresh token rotation with reuse detection at the authorisation server.
- Introduce a BFF for the highest-risk app first; run old and new paths side by side behind a feature flag so you can roll back without forcing users to sign in again.
- Where a BFF is not possible, move tokens to memory and a worker, add DPoP, and test reload and multi-tab behaviour with a pilot group.
- Add
Clear-Site-Dataand client-side clearing, then the CI storage test as a release gate.
Framework mapping
| Control | OWASP ASVS 5.0 | NIST SP 800-53 Rev. 5 | NIST CSF 2.0 | ATT&CK technique reduced |
|---|---|---|---|---|
| HttpOnly, prefixed session cookies | V3.3.1, V3.3.3, V3.3.4 | SC-23 | PR.DS-10 | T1539 Steal Web Session Cookie |
| No sensitive data in browser storage | V14.3.3 | SC-28 | PR.DS-01 | T1555.003 Credentials from Web Browsers |
| Clearing storage at logout | V14.3.1, V7.4.1 | AC-12 | PR.DS-01 | T1185 Browser Session Hijacking |
| Sender-constrained tokens (DPoP) | n/a | SC-23 | PR.DS-10 | T1528 Steal Application Access Token |
| Content Security Policy against injected script | V3.4.3 | n/a | PR.DS-10 | T1059.007 JavaScript |
Common failure patterns
- "HttpOnly cookies are vulnerable to CSRF, so localStorage is safer": trading a solvable problem (CSRF, fixed by SameSite and tokens) for an unsolvable one (script-readable tokens).
- Long-lived refresh tokens in localStorage: one XSS or one infostealer run yields months of access; see the Infostealer Logs and Session Token Abuse Guide.
- Encrypting tokens in localStorage with a key in the same JavaScript: adds code, not security; the attacker's script calls the same decrypt function.
- Several apps on one origin: a marketing CMS page with an XSS bug reads the customer portal's tokens because both live on
www. - Logout that only deletes the cookie: cached API responses, IndexedDB records and other tabs keep personal data and tokens.
- Trusting storage as input: values read from localStorage inserted with
innerHTML, turning a one-off XSS into a persistent one.
Lessons from incidents
The Cyberhaven Chrome Extension Breach 2024 shows the extension reader in practice: a malicious version of a trusted extension, live for about 30 hours, harvested cookies, session data and Facebook access tokens from users' browsers. No storage choice inside the page defends against code with that level of browser access; what limits the damage is short token lifetimes, sender-constrained tokens, server-side anomaly detection and fast revocation. Govern which extensions are allowed on managed browsers, and assume tokens on unmanaged devices may be copied.
Practitioner checklist
- Default to cookie sessions or a BFF; keep OAuth tokens out of the browser for sensitive apps.
- Use
__Host-session cookies withSecure,HttpOnly, explicitSameSiteand short lifetimes. - If an SPA must hold tokens, keep access tokens in memory, rotate refresh tokens and bind both with DPoP and a non-extractable key.
- Never store access tokens, refresh tokens or personal data in localStorage.
- Isolate applications on separate hosts, not paths.
- Treat values read from storage as untrusted input.
- Revoke server-side, send
Clear-Site-Dataand clear storage in code at logout and timeout. - Exclude authenticated responses from service worker caches.
- Run an automated sign-in and logout storage test in CI.
- Deploy a reporting Content Security Policy and act on violation reports.
Standards and references
- IETF: RFC 10017 OAuth 2.0 for Browser-Based Applications
- IETF: RFC 9449 OAuth 2.0 Demonstrating Proof of Possession (DPoP)
- OWASP: Application Security Verification Standard 5.0
- OWASP: HTML5 Security Cheat Sheet
- MDN: Set-Cookie header
- MDN: Clear-Site-Data header
- MDN: Storage quotas and eviction criteria
- MDN: State partitioning
Related NHI Mgmt Group resources: OAuth for Browser-Based Applications and the BFF Pattern Guide · Token and Session Security Guide · Cookie Security Attributes Guide · Client-Side Security Guide