What is the difference between localStorage, sessionStorage and cookies?
Quick Answer
localStorage — key/value, ~5MB, persists until cleared, per origin, not sent to the server. sessionStorage — same but cleared when the tab closes. Cookies — small (~4KB), sent with every request to the domain, can be HttpOnly (invisible to JS) and Secure/SameSite.
localStorage and sessionStorage are both key/value stores of a few megabytes, per origin, and neither is ever sent to the server — the difference is localStorage sticks around and sessionStorage clears when the tab closes. Cookies are tiny, and they're automatically attached to every request to that domain, which is why they're used for auth, and they can be marked HttpOnly so JavaScript can't touch them. The security point is that you shouldn't put an access token in localStorage, because any cross-site-scripting bug can read it — a memory variable or an HttpOnly cookie is safer.
- Web Storage is synchronous and string-only (JSON your objects).
- Cookies are the right place for auth that the server needs on every request — and
HttpOnlykeeps them away from XSS. - Don't store JWTs / access tokens in
localStorage— any XSS can read them. Memory or anHttpOnlycookie is safer. - For larger client data use IndexedDB (async, structured, much bigger).