LocalStorage, SessionStorage & Cookies
📖 Concept
The Web Storage API provides mechanisms to store data in the browser. Each has different characteristics:
| Feature | LocalStorage | SessionStorage | Cookies |
|---|---|---|---|
| Capacity | ~5-10 MB | ~5 MB | ~4 KB |
| Expiry | Never (persists) | Tab close | Configurable |
| Sent to server | No | No | Yes (every request!) |
| Scope | Origin-wide | Tab-specific | Path-configurable |
🏠 Real-world analogy: LocalStorage is like a permanent locker — your stuff stays until you empty it. SessionStorage is a day locker — cleared when you leave. Cookies are like a visitor badge — shown at every checkpoint.
💻 Code Example
1// LocalStorage — persists across sessions2localStorage.setItem("theme", "dark");3localStorage.setItem("user", JSON.stringify({ name: "Alice", age: 25 }));4const theme = localStorage.getItem("theme"); // "dark"5const user = JSON.parse(localStorage.getItem("user"));6localStorage.removeItem("theme");7localStorage.clear(); // Remove everything89// SessionStorage — same API, cleared on tab close10sessionStorage.setItem("tempData", "hello");1112// Cookies — more complex13document.cookie = "username=Alice; max-age=86400; path=/; SameSite=Strict";14document.cookie = "theme=dark; expires=Fri, 31 Dec 2025 23:59:59 GMT";1516// Reading cookies (returns all as one string)17console.log(document.cookie); // "username=Alice; theme=dark"1819// Helper function to get specific cookie20function getCookie(name) {21 const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));22 return match ? decodeURIComponent(match[2]) : null;23}2425// Delete cookie (set expired date)26document.cookie = "username=; max-age=0";2728// Storage event — listen for changes in OTHER tabs29window.addEventListener("storage", (e) => {30 console.log(`Key: ${e.key}, Old: ${e.oldValue}, New: ${e.newValue}`);31});
🏋️ Practice Exercise
Mini Exercise:
- Build a theme toggle that persists across page reloads using localStorage
- Create a shopping cart that saves items to localStorage
- Implement a "Remember me" login using cookies with proper expiry
- Build a form that auto-saves draft content to sessionStorage
⚠️ Common Mistakes
Storing sensitive data (passwords, tokens) in localStorage — it's accessible by any script on the page (XSS risk)
Forgetting to
JSON.stringify()objects before storing andJSON.parse()when retrievingNot handling the case when
getItem()returnsnull—JSON.parse(null)returnsnull, not an errorSetting cookies without
Secure,HttpOnly, andSameSiteflags — security vulnerabilityExceeding storage limits without error handling — use try/catch around
setItem
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for LocalStorage, SessionStorage & Cookies. Login to unlock this feature.