localStorage vs sessionStorage vs Cookies
Three client-side storage mechanisms with different lifetimes, size limits, and use cases.
| Feature | localStorage | sessionStorage | Cookies |
|---|---|---|---|
| API | setItem/getItem/removeItem | setItem/getItem/removeItem | document.cookie (awkward) |
| Best for | User preferences, theme, cached data | Form data, temporary state per tab | Authentication tokens, server-readable state |
| Lifetime | Permanent (until manually cleared) | Until tab/window closes | Configurable (expires/max-age) |
| Size limit | ~5-10 MB | ~5-10 MB | ~4 KB per cookie |
| Accessible from | Same origin | Same origin, same tab | Configurable (domain, path, SameSite) |
| Sent with requests | No | No | Yes (every HTTP request) |
Verdict
Use localStorage for persistent client-side data. Use sessionStorage for per-tab temporary data. Use cookies only for data the server needs to read (auth tokens). Never store sensitive data in any of these without encryption.
Code Example
Related Tutorials
Related Glossary Terms
JavaScript Object Notation — a lightweight text format for data exchange. JSON supports strings, numbers, booleans, null, objects, and arrays. It's the standard format for API responses and configuration files.
JWTJSON Web Token — a compact, URL-safe token format for securely transmitting information between parties. A JWT has three parts: header, payload, and signature. Commonly used for authentication in APIs.
Local StorageA web browser API for storing key-value pairs persistently (survives browser restarts). Limited to ~5MB per origin, stores strings only. Use JSON.stringify/JSON.parse for objects. Session Storage is similar but clears when the tab closes.