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.

StorageUseful whenMain cost or constraint
CookiesThe server must receive a small value with matching HTTP requestsSent repeatedly; strict size limits; needs security attributes
localStorageA small string preference should survive browser restartsSynchronous access can block the main thread
sessionStorageA small string value belongs to one tab sessionDisappears with that session and is not shared like persistent storage
IndexedDBThe page needs asynchronous access to larger structured dataMore 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

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →