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

codeTap to expand ⛶
1// LocalStorage — persists across sessions
2localStorage.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 everything
8
9// SessionStorage — same API, cleared on tab close
10sessionStorage.setItem("tempData", "hello");
11
12// Cookies — more complex
13document.cookie = "username=Alice; max-age=86400; path=/; SameSite=Strict";
14document.cookie = "theme=dark; expires=Fri, 31 Dec 2025 23:59:59 GMT";
15
16// Reading cookies (returns all as one string)
17console.log(document.cookie); // "username=Alice; theme=dark"
18
19// Helper function to get specific cookie
20function getCookie(name) {
21 const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
22 return match ? decodeURIComponent(match[2]) : null;
23}
24
25// Delete cookie (set expired date)
26document.cookie = "username=; max-age=0";
27
28// Storage event — listen for changes in OTHER tabs
29window.addEventListener("storage", (e) => {
30 console.log(`Key: ${e.key}, Old: ${e.oldValue}, New: ${e.newValue}`);
31});

🏋️ Practice Exercise

Mini Exercise:

  1. Build a theme toggle that persists across page reloads using localStorage
  2. Create a shopping cart that saves items to localStorage
  3. Implement a "Remember me" login using cookies with proper expiry
  4. 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 and JSON.parse() when retrieving

  • Not handling the case when getItem() returns nullJSON.parse(null) returns null, not an error

  • Setting cookies without Secure, HttpOnly, and SameSite flags — security vulnerability

  • Exceeding 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.