What is the difference between localStorage, sessionStorage and cookies?
Three client-side storage mechanisms with different lifetimes, sizes, and — most importantly — different exposure.
- localStorage — around 5-10MB, persists until explicitly cleared, shared across every tab on the origin, and never sent to the server. Synchronous string-only API.
- sessionStorage — the same API and roughly the same size, but scoped to a single tab and cleared when that tab closes. Two tabs on the same site have entirely separate sessionStorage.
- Cookies — only about 4KB, and sent with every HTTP request to the origin, which is both their purpose and their cost. They have an explicit expiry and, crucially, security attributes the other two lack.
The point interviewers are usually driving at: where to keep an authentication token. localStorage is readable by any JavaScript on the page, so a single XSS vulnerability hands over every user's session. A cookie marked httpOnly cannot be read by JavaScript at all; adding secure restricts it to HTTPS and sameSite defends against CSRF. That is why httpOnly cookies are the recommended place for session tokens and localStorage is not.
Note: For structured or larger data, IndexedDB is the right answer — asynchronous, far larger, and it stores real objects rather than strings.





