JavaScript Storage
Use localStorage and sessionStorage to persist data in the browser across sessions and refreshes.
TL;DR
- 01Use
localStorageto save data that persists across browser sessions. - 02Use
sessionStoragefor temporary data cleared when the tab closes. - 03Store only strings by converting objects to
JSONfirst.
Tips
- 01Use
localStoragefor user preferences andsessionStoragefor temporary state, then sync between tabs usingstorageevents. - 02Wrap
JSON.parse()calls in atry/catchblock because corrupted or manually edited storage data throws exceptions.
Warnings
- 01Avoid storing sensitive data like passwords or tokens in
localStoragebecause it is vulnerable to cross-site scripting attacks. - 02Saving an object directly without
JSON.stringify()stores the useless string[object Object]instead of your data.
localStorage Basics
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!");
}sessionStorage
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();Storing Objects
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 Events
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);
}
});Best Practices
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 insteadIn Practice
Saves and loads user interface preferences using JSON serialization while handling storage quotas and parsing errors.
- 01Create a preferences object containing the user's selected theme and font size.
- 02Serialize the preferences object to a JSON string and store it safely in
localStorage. - 03Catch any storage quota errors that might arise if the browser storage is full.
- 04Retrieve and parse the stored JSON string back into a JavaScript object when the page loads.
- 05Fallback to default values if preferences are missing or the string contains invalid data.
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 };
}
}FAQ
The 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.