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.
| Property | localStorage | Cookies | IndexedDB |
|---|---|---|---|
| Sent to server | Never automatically | With every matching request | Never automatically |
| Scope | Origin | Host or domain plus path, with SameSite rules | Origin |
| Lifetime | Until cleared or evicted | Session or Expires/Max-Age | Until cleared or evicted |
| Typical size | About 5 MiB per origin | About 4 KB per cookie | Large, governed by origin quota |
| Data model | String key-value | Name-value with attributes | Structured objects, indexes, transactions |
| API style | Synchronous | Header-based; document.cookie or Cookie Store API | Asynchronous, event based; wrappers can expose promises |
| Readable by script | Yes | Unless HttpOnly | Yes |
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.