JavaScript Local Storage and Session Storage
Use the Web Storage API to remember small text values in a browser. Learn when to choose localStorage or sessionStorage, how to save JSON, and how to handle unavailable storage.
Choose localStorage or sessionStorage
Both storage areas are separated by website origin and store string values. localStorage is intended to remain after a browser session ends, while sessionStorage is scoped to a page session and is cleared when that session ends. Browser privacy settings can affect storage behavior.
Save and read a string
Use the Storage methods rather than treating the storage object like a regular JavaScript object. The example catches errors because browser settings or storage limits can prevent an operation.
const preferenceKey = "site-theme";
try {
localStorage.setItem(preferenceKey, "dark");
const savedTheme = localStorage.getItem(preferenceKey);
console.log(savedTheme); // "dark"
} catch (error) {
console.error("Browser storage is unavailable:", error);
}
Store an object as JSON
Web Storage stores strings. Convert an object to JSON before saving it, then parse the returned string when reading it. Invalid or older data can make JSON.parse() throw, so handle that case.
const settingsKey = "site-settings";
const settings = { fontSize: "large", contrast: true };
try {
localStorage.setItem(settingsKey, JSON.stringify(settings));
const savedText = localStorage.getItem(settingsKey);
const savedSettings = savedText ? JSON.parse(savedText) : null;
console.log(savedSettings);
} catch (error) {
console.error("Could not save or read settings:", error);
}
Remove one saved value
Remove only the key your feature owns. Avoid localStorage.clear() in shared sites because it deletes every value saved for that origin, including values used by other parts of the site.
localStorage.removeItem("site-theme");
Keep storage small and safe
Web Storage operations are synchronous, so it is best for small preferences or simple state rather than large datasets. Use a database API such as IndexedDB for larger client-side data needs.
Practice a preference setting
Save a theme or display preference under a feature-specific key, read it when the page loads, and offer a control to remove that key. Review JavaScript JSON for serialization and error handling for working with storage exceptions.