Browser Storage
Ways a website can save small pieces of data in your browser so they're still there next visit.
What is it?
Normally, everything a page holds in memory (JavaScript variables, unsubmitted form input) disappears when you close the tab or navigate away. Sometimes a site needs to remember things across visits: that you're logged in, that you prefer dark mode, that you had three items in a cart.
Browsers offer a few tools for this. The choice depends on how long the data should last and who needs to see it:
- Cookies are sent automatically with every request to the server. That makes them the classic way to track a logged-in session.
- localStorage keeps data only in the browser, never sent to the server automatically. It lasts until something clears it.
- sessionStorage works like localStorage but is wiped when that tab is closed.
None of these is a full database. They're for small amounts of data, stored on one device and browser.
Explain like I'm 10
A cookie is like a stamped hand at a venue: you show it at every counter (the server) so they recognize you. localStorage is a locker at home that stays packed until you empty it. sessionStorage is a locker at the venue, cleared out when you leave for the night.
Examples
localStorage vs. sessionStorage
// Persists even after closing and reopening the browser
localStorage.setItem("theme", "dark");
// Cleared automatically once this tab is closed
sessionStorage.setItem("draftText", "Hello, world");
// Reading values back later
const theme = localStorage.getItem("theme");Both use the same key-value API. localStorage data survives closing the browser; sessionStorage data disappears when the tab closes.
A basic cookie
document.cookie = "sessionId=abc123; max-age=3600";Unlike localStorage or sessionStorage, this cookie is attached automatically to every later request this browser makes to the same site. That's how a server recognizes a returning user without any extra code.
How it works
The browser stores cookies and adds them to the headers of every request to the domain that set them. That's how a server recognizes the same visitor across requests.
localStorage and sessionStorage stay in the browser. Nothing is sent to a server automatically; JavaScript has to read and send the data if the server needs it.
All three are scoped per origin, so one website generally can't read another's stored data.
Why does it exist?
Different problems need different lifetimes and visibility. A login session needs the server to recognize you on every request, which is what cookies were built for. A saved preference or draft only needs to live in the browser, without adding data to every network request; that's what localStorage and sessionStorage are for.
When to use it
- Cookies: the server needs the value on every request, like an authentication session.
- localStorage: data that should last across visits but only matters to the browser, like a saved theme.
- sessionStorage: short-lived, per-tab data that shouldn't outlive the visit, like a multi-step form in progress.
When not to use it
None of these suit large amounts of data or anything sensitive that needs strong protection. Anyone with access to the device can read them in the browser's dev tools. Sensitive data, or data that must be shared reliably across devices, belongs on the server in a real database.
Common mistakes
Storing sensitive data like passwords in localStorage, where anyone with device or script access can read it.
Expecting sessionStorage data to survive closing the tab, when it's designed not to.
Putting lots of data in cookies, which slows down every request since cookies are sent with each one.
Practice exercises
- Easy:
Use localStorage to save a user's chosen theme, and load it back when the page reopens.
- Medium:
Build a simple multi-step form that saves progress in sessionStorage. Confirm the progress disappears after closing the tab.
- Hard:
Using a concrete scenario, explain why authentication sessions usually use cookies rather than localStorage.
Interview questions
What's the key difference between cookies and localStorage?
Cookies are sent automatically with every request to the server that set them, which suits server-side session tracking. localStorage stays in the browser and is never sent automatically.
What's the difference between localStorage and sessionStorage?
Same API. localStorage lasts until explicitly cleared; sessionStorage is cleared when its tab closes.
Why shouldn't sensitive data be stored in localStorage?
It's plain, unencrypted storage that any script on the page, or anyone with the browser's dev tools, can read. It gives no real protection.
What are the typical size limits for localStorage/sessionStorage versus a single cookie?
localStorage and sessionStorage usually allow about 5-10MB per origin (it varies by browser). A single cookie is limited to about 4KB, and browsers also cap the number of cookies per domain.
Is the localStorage/sessionStorage API synchronous or asynchronous, and why does that matter?
Synchronous: every read and write blocks the JavaScript thread until it finishes. With small data you won't notice, but large values can briefly block the main thread and make the page feel unresponsive. That's one reason it's meant for small data.
When would you reach for IndexedDB instead of localStorage?
When you need much more data, structured or queryable data (not just string key-value pairs), or async access that doesn't block the main thread. IndexedDB has indexes, transactions, and much larger quotas, but a far more complex API.
If a site is open in two different browser tabs, do they share the same localStorage data? What about sessionStorage?
localStorage is shared by every tab and window of the same origin; a write in one is visible in the others right away. sessionStorage belongs to one tab/window, so each tab has its own, even for the same site.
Does duplicating an existing browser tab preserve its sessionStorage, and does opening a fresh tab to the same URL do the same?
Duplicating a tab copies its sessionStorage, because browsers treat it as continuing the same browsing context. A new tab opened to the same URL starts empty, since it's a new top-level browsing context.
If a user clears their browser's cookies, does that also clear localStorage?
Not necessarily. They're separate mechanisms, and whether 'clear cookies' also clears other site data depends on the setting chosen ('cookies only' versus 'all site data'). Don't assume clearing one cleared the other.
What does the `HttpOnly` flag on a cookie do, and why does it matter for security?
It stops JavaScript from reading or writing the cookie via document.cookie; only the browser's HTTP layer can use it. That blocks a common XSS attack where injected script tries to steal a session cookie, because the script can't see it.
What do the `Secure` and `SameSite` cookie attributes protect against?
Secure sends the cookie only over HTTPS, so it isn't exposed on unencrypted networks. SameSite limits whether the cookie is sent with cross-site requests, which helps block CSRF attacks that rely on the browser attaching cookies to requests from another site.
Why is an auth token often stored in a cookie rather than localStorage, from a security standpoint?
A cookie can be HttpOnly, so JavaScript can't see it and an XSS attack can't steal it. Anything in localStorage is readable by any script on the page, so one XSS hole anywhere on the site can leak the token.
What does 'same-origin' mean in the context of storage scoping?
Two URLs are same-origin only if protocol, host, and port all match. localStorage/sessionStorage are strictly scoped per origin (cookies use slightly different, host-based rules), so a script on one origin generally can't read another origin's data.
How can one open tab find out that another tab just changed a value in localStorage?
Listen for the storage event on window. The browser fires it in every other same-origin tab or window when localStorage changes, with the key, old value, and new value.
Why doesn't the `storage` event fire in the same tab that made the change?
It exists so other browsing contexts can react to changes they didn't make. The tab that wrote the value already knows it, so the spec only sends the event to other tabs and windows sharing that storage.
What does `localStorage.getItem("missingKey")` return if that key was never set?
null, not undefined. Check for null (or use a falsy check) rather than undefined.
Why can localStorage only store strings, and how do you work around that to store objects?
The Web Storage API's get/setItem only take and return strings, by design. For structured data, JSON.stringify() before saving and JSON.parse() after reading.
What happens if you try to write more data than localStorage's quota allows?
setItem throws a QuotaExceededError (or similar DOMException) instead of silently failing or truncating. Wrap writes of possibly large values in try/catch.
What do a cookie's `path` and `domain` attributes control?
path limits the cookie to requests whose URL path starts with that value (e.g. /admin). domain controls which hosts get the cookie; set broadly, it can be shared across subdomains instead of only the exact host that set it.
Why might a 'remember me' login feature use a long-lived cookie rather than a long-lived value in localStorage?
The server must recognize the user on the very first request of a new visit, before any page JavaScript runs. The browser attaches a cookie to that first request by itself. localStorage is only readable after the page's script runs, which would need an extra round trip to tell the server.