How do localStorage and sessionStorage work?
Useful first: Same-origin policy · optional, not a requirement
Choose your depth
Stay with the essentials, or look closer.
YOUR GOALChoose between a remembered preference and temporary information for one tab.
Two small notebooks in the browser
Remember a preference or a temporary choice
A reading website could save your preferred text size under a name such as reader:text-size. Think of Web Storage as a notebook of named values that the website’s scripts can consult.
localStorage can keep that preference for later visits. sessionStorage could instead remember which step you reached in a temporary guide in one tab. Reloading the page does not by itself erase that tab’s sessionStorage.
[2] [3]A notebook is not a backup or a network message
Users can clear browser data, and private browsing usually removes stored data when the private session ends. A saved preference is convenient; the only copy of an important document needs a stronger recovery plan.
Unlike eligible cookies, Web Storage values are not automatically sent with HTTP requests. A script can still read and transmit them. An HTTP cache has another job: storing responses so they can be reused. Saving a text-size setting does not cache the page or make it work offline.
[1] [2] [8] [10]Use browser storage for recoverable local state, and choose the lifetime deliberately.
localStorage means the data is kept forever and never leaves the device.
Browser data can be cleared or unavailable, and a page’s scripts can send stored values over the network.
Show the explanation
sessionStorage, while still allowing for unavailable or cleared storage. sessionStorage survives reloads in a page session. It is suitable for temporary tab state, but it is not a guarantee that the data will always be available.
YOUR GOALRead a small storage operation and predict which pages can share its values.
Follow keys, origins and page sessions
Store strings and handle a missing key
The Storage API uses string keys and values. This TypeScript-compatible fragment assumes the browser permits storage:
localStorage.setItem("reader:text-size", "large");
const savedSize = localStorage.getItem("reader:text-size");
localStorage.removeItem("reader:text-size");The read returns "large"; reading the key after removal returns null. To store a plain object, explicitly serialize it with JSON.stringify and parse it when reading. Parsing reconstructs a value, not a live link to the original object. Validate the parsed shape, and handle missing or malformed data instead of assuming it is trustworthy.
The path does not create a private compartment
For ordinary pages opened directly in the same browser profile, https://guide.example/read and https://guide.example/settings share an origin and can use the same localStorage area. Changing to http://guide.example, a different subdomain or a different effective port changes the origin.
See the same-origin policy for the scheme, host and port boundary. A key prefix helps organize values; it does not stop another script in that origin from reading them. Embedded third-party contexts may face additional storage partitioning or access restrictions.
[2] [6] [8] [9]A page session is more than one page load
sessionStorage is separated by origin and top-level browsing context, usually a browser tab. Same-origin frames within that tab can share its session storage. Reloading does not start from an empty store.
A newly opened page with an opener can begin with a copy of the opener’s sessionStorage; later changes remain separate. Therefore, separate tabs do not always start with different values. Page sessions normally end when their tabs close, but browser restoration can preserve a session. Do not use tab closure as a security guarantee that secrets have been destroyed.
[3]Check the origin, the tab’s page session and the stored string before reasoning about a value.
Putting two applications in different URL folders isolates their localStorage.
Paths do not define origins. Applications on the same origin can access the same localStorage area.
Show the explanation
https://guide.example/read and https://guide.example/settings Only the second pair keeps the same scheme, host and effective port. A different path does not create another origin.
YOUR GOALHandle unavailable storage and distinguish change notifications from safe coordination.
Design for failure and shared-state limits
Make a failed write an ordinary outcome
Obtaining a storage object can throw SecurityError when browser policy denies access. A write can fail with QuotaExceededError. Put the access itself inside the protected operation:
function saveTextSize(value: "normal" | "large"): boolean {
try {
window.localStorage.setItem("reader:text-size", value);
return true;
} catch {
return false;
}
}The caller can keep the preference in memory when this returns false and avoid claiming it was saved. Reads and JSON parsing need their own handling too. Web Storage is synchronous, so large or frequent operations can delay other work on the page. Consider an asynchronous API such as IndexedDB for larger structured datasets.
[1] [5] [8]A change event is not a transaction
When a localStorage value changes, a storage event can notify other documents sharing that area, including other same-origin tabs. The writing window does not receive that event for its own write. For sessionStorage, notifications stay within documents sharing the same tab’s storage area, not independent tabs.
Suppose two tabs both read a counter as 4, then each writes 5. A read-increment-write sequence can lose an increment; a storage event does not turn it into a lock or transaction. Do not use that sequence to allocate unique identifiers or enforce a cross-tab limit.
Treat stored values as untrusted input
A script executing in the page’s origin, including injected code exploiting cross-site scripting, may read or modify its Web Storage. A shorter lifetime does not make sessionStorage a secret vault. Avoid storing sensitive credentials or session identifiers there, and do not let a client-stored flag decide whether the server grants access.
For example, a value saying isAdmin=true is a claim from the client, not proof of permission. Validate stored values before use and preserve the server’s authorization checks.
Expect storage to fail, keep operations small and never treat client data or notifications as authority.
A storage event makes updates from multiple tabs atomic.
It reports changes to other documents. It does not lock a multi-step read-modify-write sequence.
Show the explanation
An increment may be lost; storage events do not provide a transaction for this sequence. The individual calls do not make the combined sequence a transaction. Both tabs can base their writes on the same earlier value.
Keep asking. Check the details.
Source-checked using AI (OpenAI Codex) on . The checks covered sources, examples, and quizzes for this article version.
No human review is claimed. AI review can miss errors; check the original sources below.
- HTML Standard — Web storage
- MDN — Window.localStorage
- MDN — Window.sessionStorage
- MDN — Using the Web Storage API
- MDN — Web Storage API
- MDN — Same-origin policy
- MDN — Window storage event
- MDN — Storage quotas and eviction criteria
- OWASP — HTML5 Security: Local Storage
- MDN — HTTP caching