Join our Newsletter — 33% off our NHI Course
Home› Guides› Browser Storage Security Guide: localStorage, IndexedDB and Token…
Guide Web & API Security

Browser Storage Security Guide: localStorage, IndexedDB and Token Storage Choices

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 27 October 2026 15 min read
On this page

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

MechanismScopeLifetimeReadable by page scriptSent to server automaticallyTypical capacity
HttpOnly cookieHost or domain and path, per attributesSession or Max-Age/ExpiresNoYes, subject to SameSiteSmall (around 4 KB per cookie)
Script-readable cookieAs aboveAs aboveYes, via document.cookieYesSmall
localStorageOrigin, all tabsUntil cleared or evictedYes, synchronouslyNo5 MiB per origin (MDN)
sessionStorageOrigin, one tabUntil the tab closesYesNo5 MiB per origin (MDN)
IndexedDBOrigin, all tabs and workersUntil cleared or evictedYes, asynchronously, including from service workersNoLarge, quota-managed
Cache APIOriginUntil cleared or evictedYesNoLarge, quota-managed
JavaScript memory (closure, worker)One page or workerUntil reloadOnly by code in that contextNoNot 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.

ThreatHttpOnly cookieWeb Storage and IndexedDBIn-memory tokenNon-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 exfiltrateReadable by code in the same context, harder to findCannot export, but can sign proofs while the page is open
Malicious or hijacked browser extension (T1176.001)Readable with cookie permissionsReadable via content scriptsReadable via page injectionUsable while the page is open
Infostealer malware on the device (T1555.003, T1539)Copied from the profile on diskCopied from the profile on diskNot persistedKey material not exportable through the API; on-disk protection depends on the browser
Another app on the same originShared if path or domain overlapFully shared (no path scoping)IsolatedShared if stored in the same origin's IndexedDB
Someone with the unlocked deviceVia developer toolsVia developer toolsWhile the tab is openUsable 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 storingRecommendedAcceptable with conditionsAvoid
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 itAny Web Storage; script-readable cookies
OAuth access token in an SPAMemory only, minutes-long lifetime, DPoP-boundsessionStorage to survive reloads, with short lifetimelocalStorage; long-lived bearer tokens
OAuth refresh token in an SPANot in the browser (BFF or token-mediating backend)Isolated in a Web Worker, rotated on every use, DPoP-bound, absolute lifetimelocalStorage or IndexedDB with no binding
DPoP or other signing keyWebCrypto key generated with extractable: false, stored in IndexedDBRegenerate per session if persistence is unreliableExportable keys; keys in JSON in Web Storage
ID token and user profileServer-side, or minimal claims in memoryNon-sensitive display fields in sessionStorageFull ID token or personal data in localStorage
Offline application dataIndexedDB or OPFS with only the data the feature needsEncrypted with a key that requires user presence to unlockRegulated 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 through exportKey() or wrapKey(). Store the CryptoKey object 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 is Secure, set over HTTPS, has Path=/ and no Domain, which pins it to one host and stops a sibling subdomain from overwriting it. The newer __Http- and __Host-Http- prefixes also require HttpOnly, so the cookie cannot be set from JavaScript. Browsers without prefix support accept prefixed cookies anyway, so prefixes are defence in depth.
  • SameSite: Strict or Lax for session cookies; None requires Secure and 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-Age takes precedence over Expires. Use session cookies or short Max-Age plus 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 requires Secure; MDN recommends a __Host- prefix with it.
  • Path is not isolation: MDN states that Path is 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

  1. 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.
  2. 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.
  3. 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 with BroadcastChannel) so they discard their copies.
  4. 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.setItem and 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-Data on 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 with HttpOnly and an explicit SameSite.
  • 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

  1. Inventory every value written to browser storage, with owner and purpose.
  2. Remove sensitive data that is not a token, and move render caches to sessionStorage or memory.
  3. Shorten access token lifetime and enable refresh token rotation with reuse detection at the authorisation server.
  4. 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.
  5. 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.
  6. Add Clear-Site-Data and client-side clearing, then the CI storage test as a release gate.

Framework mapping

ControlOWASP ASVS 5.0NIST SP 800-53 Rev. 5NIST CSF 2.0ATT&CK technique reduced
HttpOnly, prefixed session cookiesV3.3.1, V3.3.3, V3.3.4SC-23PR.DS-10T1539 Steal Web Session Cookie
No sensitive data in browser storageV14.3.3SC-28PR.DS-01T1555.003 Credentials from Web Browsers
Clearing storage at logoutV14.3.1, V7.4.1AC-12PR.DS-01T1185 Browser Session Hijacking
Sender-constrained tokens (DPoP)n/aSC-23PR.DS-10T1528 Steal Application Access Token
Content Security Policy against injected scriptV3.4.3n/aPR.DS-10T1059.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 with Secure, HttpOnly, explicit SameSite and 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-Data and 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

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

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 27 October 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.