HuntExams Academy logo
HTML/CSSIntermediate#storage#javascript

What is the difference between localStorage, sessionStorage, and cookies?

Answer

localStorage persists indefinitely (~5-10MB) until cleared, scoped per origin. sessionStorage persists only for the tab session. Cookies are small (~4KB), sent with every HTTP request to the server, and can have expiry dates — used for server-side session tracking.

Example

localStorage.setItem('theme', 'dark');
sessionStorage.setItem('draft', 'hello');
document.cookie = 'user=john; max-age=3600; path=/';

Detailed explanation

localStorage, sessionStorage, and cookies store data in the browser, but differ in lifetime, scope, capacity, and communication with the server. localStorage and sessionStorage are part of the Web Storage API: both store string key–value pairs and expose methods such as setItem(), getItem(), and removeItem(). Cookies are managed through HTTP headers or document.cookie. The main interview distinction is that Web Storage remains client-side unless your code explicitly sends it, whereas the browser automatically attaches eligible cookies to HTTP requests.

localStorage is scoped to an origin: the combination of scheme, hostname, and port. It is shared by same-origin tabs and normally survives reloads and browser restarts because it has no built-in expiry. However, users, browser policies, or private-browsing cleanup can remove it, so “persists indefinitely” is not a guarantee. sessionStorage is scoped to both the origin and the top-level browsing context, usually a tab. It survives reloads but normally disappears when that tab’s session ends. A newly opened tab can sometimes receive an initial copy from its opener, but subsequent changes are independent. Both APIs are synchronous, so large or frequent operations can block JavaScript execution. Storage quotas vary by browser; Web Storage commonly offers several megabytes, not a universal guaranteed limit.

Cookies are much smaller, typically limited to about 4 KB per cookie, including associated overhead. Their request scope is controlled by attributes such as Domain and Path, rather than Web Storage’s exact-origin rule. Max-Age or Expires creates a persistent cookie; without either, it is a session cookie, although browser session restoration can preserve it. Cookies are sent only with matching, eligible requests, subject to attributes and browser privacy policies—not literally every HTTP request. Secure restricts transmission to HTTPS, HttpOnly prevents JavaScript access, and SameSite controls cross-site inclusion.

Choose localStorage for non-sensitive preferences such as a theme, sessionStorage for temporary tab-specific drafts, and cookies for server-recognised session identifiers. For authentication, server-set Secure, HttpOnly cookies are often preferable to JavaScript-readable storage, alongside appropriate CSRF protections. Neither Web Storage API protects secrets from injected same-origin scripts. Interviewers look for these practical trade-offs, not just memorised size and lifetime differences.

Key points to remember

  • localStorage persists across browser sessions and is shared by same-origin tabs; it has no automatic expiry.
  • sessionStorage is origin- and tab-scoped, survives reloads, and normally ends with the tab session.
  • Both Web Storage APIs are synchronous and store strings; objects require serialisation.
  • Cookies hold roughly 4 KB each and accompany eligible HTTP requests; Web Storage data is not sent automatically.
  • Use Secure, HttpOnly, and SameSite appropriately for session cookies; avoid storing secrets in JavaScript-readable storage.

Common mistakes candidates make

  • Claiming localStorage is permanent or that every browser guarantees the same storage quota.
  • Saying sessionStorage is cleared on reload or is shared across all same-origin tabs.
  • Saying cookies accompany every request, or assuming JavaScript can set an HttpOnly cookie.

Likely follow-up questions

How do you store an object in localStorage?

Serialise it with localStorage.setItem('user', JSON.stringify(user)), then retrieve and parse the string with JSON.parse(). Handle missing values, invalid JSON, and storage failures rather than assuming reads and writes always succeed.

Why are HttpOnly cookies useful for authentication?

HttpOnly prevents JavaScript from reading the cookie, reducing direct session-token theft through XSS. It does not eliminate XSS or CSRF: malicious scripts can still initiate authenticated actions, and cookie-based authentication needs appropriate CSRF defences.

How can localStorage changes be detected in another tab?

Listen for the storage event in other same-origin tabs. The event fires when another document changes the shared storage area, not in the document that made the change.

Interview tip: Compare lifetime, scope, capacity, and server transmission first, then give one suitable use case and one security consideration for each option.

Related Interview Questions

1
HTML/CSSAdvanced#storage#javascript

What is IndexedDB used for?

Open
2
HTML/CSSAdvanced#storage#pwa

What is the Cache API and how does it relate to Service Workers?

Open
3
HTML/CSSIntermediate#css#specificity

What is CSS specificity and how is it calculated?

Open