Topic 33 of 37
Local vs Session
Overview
The Web Storage API provides mechanisms to store key/value pairs in the browser intuitively. localStorage persists even when the browser is closed. sessionStorage is cleared when the page session ends (tab is closed). Both only store strings.
Syntax
Capacity is around 5MB per origin. It is synchronous and blocks the main thread, so don't store massive data sets here.
Using Storage API
javascript
const userSettings = { theme: "dark", volume: 80 };
// Storing data (Must stringify objects!)
localStorage.setItem('settings', JSON.stringify(userSettings));
// Retrieving data
const saved = localStorage.getItem('settings');
if (saved) {
const parsed = JSON.parse(saved);
console.log(parsed.theme); // "dark"
}
// Removing data
localStorage.removeItem('settings');
// localStorage.clear(); // clears EVERYTHINGCommon Pitfalls
- Forgetting to JSON.parse() when reading, and trying to access properties on a string.
Interview Tips
- Do NOT store sensitive information (like JWT tokens or passwords) in localStorage, as it is vulnerable to XSS (Cross-Site Scripting) attacks. Use HttpOnly Cookies instead.
Real-World Example
Remembering if a user dismissed a banner.
example
javascript
if (!localStorage.getItem('bannerDismissed')) {
showBanner();
}
closeBtn.addEventListener('click', () => {
localStorage.setItem('bannerDismissed', 'true');
hideBanner();
});