← Glossary

What Is localStorage?

localStorage is a browser Web Storage API that keeps string key-value data across sessions. Its access boundary begins with the origin, with further partitioning and retention rules controlled by the browser.

Updated:

localStorage is a browser storage area, exposed through the Web Storage API, that lets scripts on a web page save string key-value pairs that remain available after the tab and the browser are closed. The basic boundary is the origin: scheme, host and port. Pages sharing a storage area can read and write it, though browser partitioning can separate the same origin across different embedding sites. Unlike cookies, nothing in localStorage is sent to the server automatically; the data stays in the browser until a script removes it, the user clears site data, or the browser evicts it under its own policies. The feature is specified in the HTML Standard and is widely supported in modern browsers.

The name describes its two defining traits. It is local, held on the device rather than on a server, and it is storage that persists, as opposed to sessionStorage, which uses the same interface but is tied to a single tab and disappears when that tab closes. Both are deliberately simple: a flat map of strings with a handful of methods and no query language.

Reading and Writing Key-Value Data

The window.localStorage property returns a Storage object. Scripts call setItem to add or overwrite a value, getItem to read one, removeItem to delete one and clear to empty the whole store for the origin. A length property and a key method allow iteration. Keys and values are stored as strings, so anything else has to be serialized first, usually with JSON.stringify on the way in and JSON.parse on the way out. Numbers used as keys are converted to strings automatically.

Every call is synchronous. The script blocks until the read or write completes, which is convenient for small preferences but a problem for large or frequent writes on the main thread. MDN's guidance is to keep operations small and to move heavy or performance-sensitive data to an asynchronous API. The HTML Standard also warns that there is no locking: two tabs from the same origin can interleave read-modify-write sequences, and the specification does not define how storage behaves across processes in a multiprocess browser.

Changes are observable from other documents. When an operation actually changes the store, a storage event is sent to other eligible documents sharing that storage area. It includes the affected key and values where applicable; clear uses null values. The event does not fire in the tab that made the change. This makes localStorage a crude channel for coordinating tabs, for example to tell them that a user has signed out.

Origin Scope and Lifetime

Origin storage boundaries still apply inside browser partitions. A page at https://example.com cannot read what http://example.com stored, because the scheme differs, and a subdomain gets its own store rather than sharing the parent's. There is no equivalent of the cookie Domain attribute to widen access. Third-party code behaves according to where it runs: a script included with a script tag runs in the embedding page's context and writes to the embedder's store, while a script inside an iframe runs with the iframe's origin and writes there. Browsers can block third-party storage or partition it by the top-level site, with policy-dependent exceptions, and documents with an opaque origin, such as data URLs or sandboxed frames without same-origin permission, get a SecurityError when they touch the property.

Lifetime is often described as permanent, and that overstates it. The data has no expiry time of its own, which distinguishes it from cookies with Max-Age, but several things can end it:

  • a script on the origin calls removeItem or clear;
  • the user clears site data or cookies, since browsers typically clear Web Storage alongside cookies;
  • the browser evicts the origin's data under storage pressure, where best-effort data from the least recently used origins goes first;
  • WebKit documents a tracking-prevention cap after seven days of Safari use without site interaction, with separate treatment for home-screen web apps;
  • in private browsing, the data is normally discarded when the relevant private session ends; closing one window may not end a session shared with other private windows.

Capacity is also bounded. MDN documents a limit of about 5 MiB of localStorage per origin in current browsers, and a write that exceeds the quota throws a QuotaExceededError that code should catch. The HTML Standard's privacy section explicitly permits user agents to expire or clear stored data and to treat persistent storage like cookies, precisely because a unique identifier in localStorage could otherwise be used for cross-session tracking.

localStorage vs Cookies and IndexedDB

The three mechanisms answer different questions, and choosing between them depends on who needs the data and how much of it there is.

PropertylocalStorageCookiesIndexedDB
Sent to serverNever automaticallyWith every matching requestNever automatically
ScopeOriginHost or domain plus path, with SameSite rulesOrigin
LifetimeUntil cleared or evictedSession or Expires/Max-AgeUntil cleared or evicted
Typical sizeAbout 5 MiB per originAbout 4 KB per cookieLarge, governed by origin quota
Data modelString key-valueName-value with attributesStructured objects, indexes, transactions
API styleSynchronousHeader-based; document.cookie or Cookie Store APIAsynchronous, event based; wrappers can expose promises
Readable by scriptYesUnless HttpOnlyYes

Cookies exist so that the server can recognize the client; a server-managed session identifier is commonly placed in a cookie with HttpOnly, Secure and appropriate SameSite settings. localStorage exists so that the client can remember things for itself: a theme preference, a draft of a form, the last tab a user opened, a cached copy of configuration that is cheap to refetch. IndexedDB is the choice when the data is large, structured or needs indexed lookup, for example an offline mail cache. Its asynchronous, transactional design also avoids the main-thread blocking that makes big localStorage writes a bad idea.

Typical Uses

Single-page applications use localStorage for user interface state that should survive a reload: collapsed panels, chosen language, dismissed notices. Forms save drafts so that an accidental refresh does not lose a long entry. Feature flags or non-sensitive configuration fetched once can be stored so that later visits render immediately before the network answers. Analytics and consent libraries may also keep identifiers or consent state there, making this store relevant to tracking controls as well as application functionality. Testing and automation frameworks read and seed localStorage to put an application into a known state, and browser profile tools that isolate sessions keep each profile's storage areas separate for the same reason.

Limitations and Security Considerations

Anything in localStorage is readable by any script running on the origin. A single cross-site scripting flaw therefore exposes the entire store, and the attacker can also write to it, so stored values must be treated as untrusted input when read back. The OWASP HTML5 Security Cheat Sheet advises against keeping session identifiers or other sensitive data there, recommends HttpOnly cookies for session tokens because scripts cannot read them, and suggests sessionStorage when persistence is not needed. Web Storage provides no secret-storage guarantee. Profile access or device compromise can expose persisted data; operating-system access controls and disk encryption affect that risk. HttpOnly limits script access to a cookie but does not make an XSS-compromised application safe.

Beyond security, the practical limits are the string-only model, the small quota, the blocking API and the lack of any guarantee that data will still be there tomorrow. Code should handle a missing key the same way it handles a first visit, catch QuotaExceededError on writes, and never use localStorage as the only copy of something that matters. It is a convenient cache and preference store, not a database and not a vault.

Frequently asked questions

Is localStorage sent with HTTP requests?

Not automatically. A script must read a value and explicitly attach it to a request if the server needs it. Cookies instead follow the browser’s automatic request rules, including domain, path, security and same-site restrictions. Local storage can still reach a server through application code.

Can users clear localStorage?

Yes. Browser site-data controls and developer tools can remove it. Private browsing normally discards it at the end of the relevant private session, and browser retention or tracking-prevention policies may remove it sooner. Cookie-only deletion and broader site-data deletion are not identical in every browser interface.

Is it safe to store secret tokens there?

It is a poor default for authentication secrets because scripts running in that context can read it. An XSS flaw may steal or alter stored values. OWASP recommends keeping session identifiers out of Web Storage; an HttpOnly cookie can reduce script-readable token exposure, though it does not prevent every action an injected script could perform.

How much can localStorage hold?

Roughly 5 MiB per origin in current browsers, according to MDN, with the exact figure depending on the browser. Writes beyond the limit throw a QuotaExceededError. Applications that need more space or structured data should use IndexedDB, which draws on the much larger origin quota.

Do subdomains share localStorage?

No. Storage is keyed by origin, so app.example.com and example.com have separate stores, and so do the http and https versions of the same host. Unlike cookies, there is no Domain attribute to widen access; pages on different origins would have to exchange data through messaging or a server.