Browser Storage: localStorage & sessionStorage
1. Simple Definition
Web Storage API hume user ke computer/browser ke andar data (jaise Dark Mode setting, To-Do list items, ya shopping cart) save karne ki power deta hai. localStorage me data tab tak rehta hai jab tak user khud browser history delete na kare (even after system restart!). sessionStorage me data sirf tab tak rehta hai jab tak browser tab open hai (tab band hote hi data khatam).
2. Real-Life Analogy
• localStorage (Permanent Locker): Aapne locker me jo gold rakh diya, agle saal aao ya 5 saal baad, saman wahi milega (Permanent memory).
• sessionStorage (Hotel Room Keycard): Jab tak aap hotel me stay kar rahe hain (tab open hai), keycard chalta hai. Jaise hi checkout kiya (tab close), keycard expire ho jata hai!
3. Why Do We Need It?
Bina storage ke agar user page refresh (F5) karega, toh uska saara unsaved data, selected dark theme aur cart items turant gayab ho jayenge. Storage zero database ke client-side state persist karti hai.
4. Syntax & The JSON Stringify/Parse Rule
// 1. Storing Plain Strings
localStorage.setItem("user_theme", "dark");
const savedTheme = localStorage.getItem("user_theme"); // "dark"
// 2. Storing Objects / Arrays (CRITICAL: Must convert to JSON string!)
const cart = [
{ id: 101, title: "Headphones", price: 1999 },
{ id: 102, title: "Backpack", price: 899 }
];
// SAVE: Object -> String
localStorage.setItem("my_cart", JSON.stringify(cart));
// READ: String -> Object
const retrievedCart = JSON.parse(localStorage.getItem("my_cart"));
console.log(retrievedCart[0].title); // "Headphones"
// 3. Remove or Clear
localStorage.removeItem("user_theme"); // Single key delete
localStorage.clear(); // Sabhi keys permanently delete!
5. Basic Example (Theme Persistence in Action)
// Auto-apply theme on page load
function applySavedTheme() {
const currentTheme = localStorage.getItem("preferred_theme") || "light";
document.documentElement.setAttribute("data-theme", currentTheme);
}
function toggleTheme() {
const current = document.documentElement.getAttribute("data-theme");
const next = current === "dark" ? "light" : "dark";
// Save to browser locker
localStorage.setItem("preferred_theme", next);
document.documentElement.setAttribute("data-theme", next);
}
6. Output / Expected Result
7. Code Explanation: Storage Comparison Matrix
| Feature | localStorage | sessionStorage | Cookies (Document.cookie) |
|---|---|---|---|
| Capacity | ~5 MB - 10 MB | ~5 MB | Tiny 4 KB only |
| Lifetime | Permanent (until cleared) | Current Tab session | Set by Expiry Date header |
| Server Sent? | No (Pure Client-side) | No | Yes (Every HTTP request me jata hai) |
8. Real-World Example
Isi website par jo aapka course completion progress aur Dark/Light mode theme switch hota hai, wo localStorage ke zariye hi save rehta hai bina kisi user login ke!
9. Common Mistakes: Direct Object Pass Karna
Agar aap localStorage.setItem("user", { name: "Amit" }) direct likh dete hain bina JSON.stringify kiye, toh localStorage use string me convert karke "[object Object]" save kar deta hai! Baad me JSON.parse karne par syntax crash ho jata hai.
10. Best Practices
- Sensitive data (jaise user credit card numbers, passwords, JWT auth tokens without secure flags) ko kabhi bhi localStorage me store na karein kyunki XSS attack se malicious scripts ise chura sakti hain.
- Hamesha
JSON.parse()kotry...catchme wrap karein taaki corrupted data aane par app crash na ho.
11. Try It Yourself
Playground me localStorage.setItem("learnerName", "Aapka Naam"); likhein aur console me localStorage.getItem("learnerName") inspect karein.
12. Challenge
Ek Simple Notes Widget banayein jisme textarea me type hone wala har shabd localStorage me auto-save hota rahe (input event par).
13. Interview Questions
Answer: localStorage ek Synchronous Blocking API hai. Iska matlab hai ki jab tak 5MB data read/write ho raha hota hai, browser ka main JavaScript thread pause (freeze) ho jata hai. Isliye bohot heavy data ke liye modern asynchronous IndexedDB use kiya jata hai.
14. Quick Revision
localStorage= Permanent (~5-10MB).sessionStorage= Tab duration.- Always
JSON.stringify()before saving objects. - Always
JSON.parse()after reading objects.
15. FAQ
Q1. LocalStorage ka quota limit cross hone par kya hota hai?
Browser QuotaExceededError throw karta hai.
Q2. Dusre tab me storage update hone par kaise pata lagayein?
Browser me window.addEventListener("storage", (e) => { ... }) event fire hota hai jab kisi doosre tab me storage change hoti hai!
Q3. Incognito / Private Browsing me localStorage kaise chalta hai?
Incognito window band hote hi saara localStorage automatically erase ho jata hai.
Q4. Domain boundary (Same-Origin Policy) storage par apply hoti hai?
Haan! Website A (google.com) website B (amazon.com) ka localStorage kabhi access nahi kar sakti.
Q5. IndexedDB kya hai?
Browser ke andar poora NoSQL database jisme gigabytes of data, images aur files asynchronosly store ki ja sakti hain.
Browser Storage: localStorage & sessionStorage
1. Simple Definition
Browser Web Storage allows web applications to store key-value data persistently on the client's browser. localStorage persists data indefinitely until explicitly cleared, while sessionStorage retains data only for the lifespan of the current browser tab.
2. Real-Life Analogy
• localStorage: Your personal hardbound diary at home. Write your dark mode theme preference inside, and when you open the book next year, your notes are still right there!
• sessionStorage: A temporary electronic hotel keycard. It grants access throughout your current stay, but the moment you check out and close the door (close the tab), access expires!
3. Storage Comparison Table
| Feature | localStorage | sessionStorage | Cookies |
|---|---|---|---|
| Capacity | ~5MB - 10MB | ~5MB | ~4KB |
| Lifespan | Permanent (until deleted) | Tab Session only | Configured Expiry Date |
| Sent with HTTP Requests? | ❌ No (Purely Client-side) | ❌ No | ✅ Yes (Sent with every request) |
4. Storing Objects & Arrays (JSON Serialization)
// Web Storage ONLY stores strings! Objects must be serialized via JSON:
const userPreferences = { theme: "dark", language: "english", notifications: true };
// 1. Save to localStorage
localStorage.setItem("user_prefs", JSON.stringify(userPreferences));
// 2. Read from localStorage with error safety
try {
const savedData = localStorage.getItem("user_prefs");
const parsed = savedData ? JSON.parse(savedData) : null;
console.log("Loaded Theme:", parsed?.theme);
} catch (err) {
console.error("Corrupted localStorage data:", err);
}
// 3. Clear storage
localStorage.removeItem("user_prefs");
localStorage.clear(); // Clears all keys for current origin
5. Common Mistakes
Calling localStorage.setItem("user", userObj) without JSON.stringify() coerces the object into the string "[object Object]", corrupting your data permanently! Always serialize with JSON.stringify()!
6. Best Practices
- Never store sensitive data (JWT auth tokens, passwords, credit card numbers) in
localStoragedue to XSS vulnerability. - Always wrap
JSON.parse()calls in atry/catchblock. - Listen to the
window.addEventListener("storage", ... )event to synchronize tabs.
7. Practice Exercise
Build a dark theme toggle button that saves the user's preference to localStorage and automatically restores it on page refresh.
8. Interview Questions
Answer: Any malicious third-party script or Cross-Site Scripting (XSS) vulnerability on the page can execute localStorage.getItem("token") and steal credentials. Storing tokens in HTTP-only, Secure SameSite cookies shields them from JavaScript access.
9. Summary / Cheat Card
localStoragepersists permanently per domain origin.sessionStorageclears automatically when the tab closes.- Always use
JSON.stringify()to write andJSON.parse()to read.
10. FAQ
Q1. Is Web Storage synchronous or asynchronous?
Web Storage is completely synchronous, meaning large write operations can block the main thread. For massive data needs, use IndexedDB.