Storage and browser security
Choose the right browser storage
Choose cookies, localStorage, sessionStorage, or IndexedDB according to transport, lifetime, size, and access patterns.
8 minute lesson
Choose browser storage from the job it must do, not from the shortest API.
| Storage | Useful when | Main cost or constraint |
|---|---|---|
| Cookies | The server must receive a small value with matching HTTP requests | Sent repeatedly; strict size limits; needs security attributes |
localStorage | A small string preference should survive browser restarts | Synchronous access can block the main thread |
sessionStorage | A small string value belongs to one tab session | Disappears with that session and is not shared like persistent storage |
| IndexedDB | The page needs asynchronous access to larger structured data | More code and a transactional API |
For example, a color theme can fit in localStorage. An offline product catalog belongs in IndexedDB. A server-managed session commonly uses a cookie with Secure, HttpOnly, and an appropriate SameSite policy rather than a token exposed to every script on the page.
Storage is scoped and constrained by the browser. Quotas, eviction behavior, private browsing, and user settings mean persistent data is not an infallible database. Keep important server data on the server, handle failed writes, and make cached data replaceable.
localStorage accepts only strings:
localStorage.setItem('preferences', JSON.stringify({ theme: 'dark' }))
const preferences = JSON.parse(
localStorage.getItem('preferences') ?? '{}'
)
Do not store secrets just because an API persists them. Any script running in the origin can generally access JavaScript-readable storage, including malicious script introduced by an XSS bug.
Use the Application panel to inspect the storage used by a real page. Identify the owner, lifetime, maximum plausible size, and cleanup rule for each entry. If none is clear, the storage decision is incomplete.
Lesson completed