Technology · JavaScript
JavaScript Storage
Use localStorage and sessionStorage to persist data in the browser across sessions and refreshes.
TL;DR
- 01Use localStorage to save data that persists across browser sessions.
- 02Use sessionStorage for temporary data cleared when the tab closes.
- 03Store only strings — serialize objects to JSON before saving.
localStorage Basics
- Save data to localStorage that persists even after closing the browser.
localStorage.setItem("username", "Alice"); const username = localStorage.getItem("username"); console.log(username); // "Alice" - localStorage data survives page refreshes and browser restarts.
- Data is stored per domain, so different sites have different storage.
// example.com and test.com have separate storage - Remove specific items with removeItem.
localStorage.removeItem("username"); - Clear all localStorage data with clear.
localStorage.clear(); - Check if a key exists with the in operator or getItem.
if ("username" in localStorage) { // key exists }
sessionStorage
- Save data to sessionStorage that is cleared when the tab closes.
sessionStorage.setItem("sessionId", "abc123"); const id = sessionStorage.getItem("sessionId"); - sessionStorage is useful for temporary data that shouldn't persist.
- Each tab has its own separate sessionStorage.
// Opening the same page in a new tab has empty sessionStorage - API is identical to localStorage.
sessionStorage.setItem(key, value); sessionStorage.getItem(key); sessionStorage.removeItem(key); sessionStorage.clear(); - Use sessionStorage for form state that should reset on new sessions.
Storing Objects
- Storage only holds strings, so serialize objects to JSON first.
const user = { name: "Alice", age: 30 }; localStorage.setItem("user", JSON.stringify(user)); - Parse JSON strings back to objects when retrieving.
const stored = localStorage.getItem("user"); const user = JSON.parse(stored); console.log(user.name); // "Alice" - Handle parsing errors when the stored data might be invalid.
try { const user = JSON.parse(localStorage.getItem("user")); } catch (e) { console.error("Invalid data in storage"); } - Store arrays the same way as objects using JSON.stringify.
const items = ["apple", "banana"]; localStorage.setItem("items", JSON.stringify(items));
Storage Events
- Listen for changes to storage from other tabs or windows.
window.addEventListener("storage", (e) => { console.log(`${e.key} changed to ${e.newValue}`); }); - Storage events fire in other tabs when one tab modifies storage.
// Tab A: sets a value localStorage.setItem("sync", "newValue"); // Tab B: automatically gets notified of the change - The event object contains key, newValue, oldValue, and more.
- Use this to keep tabs in sync without manual polling.
window.addEventListener("storage", (e) => { if (e.key === "theme") { applyTheme(e.newValue); } });
Best Practices
- Check available space before storing large amounts of data.
try { localStorage.setItem("data", largeString); } catch (e) { if (e.name === "QuotaExceededError") { console.log("Storage limit exceeded"); } } - Use a storage limit of ~5-10MB for most browsers.
- Namespace your keys to avoid conflicts with other code.
localStorage.setItem("app_theme", "dark"); localStorage.setItem("app_language", "en"); - Only store non-sensitive data — localStorage is not encrypted.
- Don't store authentication tokens in localStorage — use secure cookies.
Tip: Use localStorage for user preferences and sessionStorage for temporary state, then sync between tabs with storage events.
Warning: Never store sensitive data like passwords or tokens in localStorage — it's accessible to any JavaScript code on the page.