Use localStorage and sessionStorage to persist data in the browser across sessions and refreshes.
localStorage to save data that persists across browser sessions.sessionStorage for temporary data cleared when the tab closes.JSON first.localStorage for user preferences and sessionStorage for temporary state, then sync between tabs using storage events.JSON.parse() calls in a try/catch block because corrupted or manually edited storage data throws exceptions.localStorage because it is vulnerable to cross-site scripting attacks.JSON.stringify() stores the useless string [object Object] instead of your data.localStorageA browser storage object that persists key-value data indefinitely with no expiration date.
localStorage.setItem("username", "Alice");
const name = localStorage.getItem("username");removeItem()Deletes a specific key-value pair from storage by providing the key name.
localStorage.removeItem("username");clear()Wipes all stored key-value data for the current domain origin at once.
localStorage.clear();in operatorChecks if a specific storage key exists in the storage object dictionary.
if ("username" in localStorage) {
console.log("Key exists!");
}sessionStorageA storage object that maintains key-value data for the duration of the page session.
sessionStorage.setItem("tabId", "12345");
const id = sessionStorage.getItem("tabId");Tab isolationMaintains separate storage instances for each open browser tab, even on the same origin.
// A new window starts a fresh storage instanceIdentical APIShares the same storage interface, methods, and behaviors as localStorage.
sessionStorage.setItem("key", "val");
sessionStorage.removeItem("key");
sessionStorage.clear();JSON.stringify()Serializes objects or arrays into strings before saving them to browser storage.
const user = { name: "Alice", age: 30 };
localStorage.setItem("user", JSON.stringify(user));JSON.parse()Deserializes stored JSON strings back into usable JavaScript objects or arrays.
const raw = localStorage.getItem("user");
const user = JSON.parse(raw);
console.log(user.name); // "Alice"Error handlingWraps JSON parsing in try-catch blocks to prevent crashes on invalid data formats.
try {
const user = JSON.parse(localStorage.getItem("user"));
} catch (e) {
console.error("Invalid JSON stored");
}storage eventListens for storage changes on the window object across different origin tabs.
window.addEventListener("storage", e => {
console.log(`${e.key} changed to ${e.newValue}`);
});Cross-tab syncNotifies other open tabs on the same origin immediately when storage updates.
// Tab A writes to storage
localStorage.setItem("theme", "dark");
// Tab B receives storage event automaticallyStorageEvent objectExposes modified keys, new values, old values, and the target storage area.
window.addEventListener("storage", e => {
if (e.key === "theme") {
applyTheme(e.newValue);
}
});QuotaExceededErrorCatches browser storage limit exceptions to avoid crashing applications when disk space runs out.
try {
localStorage.setItem("key", largeData);
} catch (e) {
if (e.name === "QuotaExceededError") {
console.warn("Storage limit exceeded!");
}
}NamespacingPrefixes storage keys to prevent overlap conflicts with other third-party scripts.
localStorage.setItem("myApp_theme", "dark");
localStorage.setItem("myApp_lang", "en");Security warningsAvoids storing sensitive authentication tokens, passwords, or personal data in plaintext storage.
// Avoid storing JWTs in localStorage
// Secure: use HTTP-only, secure cookies insteadThe localStorage object persists data indefinitely across browser sessions and tabs. In contrast, sessionStorage is cleared automatically when the tab or window closes. Use localStorage for user preferences and sessionStorage for temporary form state.
Convert the object to a string using JSON.stringify() before saving it with localStorage.setItem(). Read it back by parsing the string with JSON.parse(). Skipping this serialization step mistakenly stores the string [object Object].
Listen for the storage event on the window object. This event fires in all other tabs when localStorage is updated. It provides the modified key, oldValue, and newValue to sync your frontend.
The localStorage.setItem() method throws a QuotaExceededError when storage limit is reached. This limit is typically five megabytes. Always wrap write operations in try/catch blocks to handle storage failures gracefully.
Call localStorage.removeItem('key') to delete a specific item. Alternatively, use localStorage.clear() to wipe all stored key-value pairs for the origin. Use clear() with caution as it clears data from all scripts.
Managing User Preference Storage
Saves and loads user interface preferences using JSON serialization while handling storage quotas and parsing errors.
localStorage.function savePreferences(theme, fontSize) {
const prefs = { theme, fontSize };
try {
const serialized = JSON.stringify(prefs);
localStorage.setItem("user_prefs", serialized);
} catch (e) {
console.error("Save failed", e);
}
}
function loadPreferences() {
const raw = localStorage.getItem("user_prefs");
if (!raw) return { theme: "light", fontSize: 14 };
try {
return JSON.parse(raw);
} catch (e) {
return { theme: "light", fontSize: 14 };
}
}Always serialize objects before storing them and use try-catch to safeguard against corrupted data or full storage.