HTML5 introduced two key storage mechanisms for the browser: localStorage and sessionStorage. These tools allow developers to store data persistently on the client-side, enabling features like remembering user settings, saving UI state, or caching data across sessions — all without needing a backend.
This article explains how each works, when to use them, and key best practices.
Web Storage is a built-in browser feature that allows you to store data in key-value pairs using JavaScript.
There are two types:
localStorage – persistent datasessionStorage – temporary, per-tab dataBoth are accessible through the window object:
window.localStorage;
window.sessionStorage;
localStorage: Persistent Across Tabs and Sessions// Save data
localStorage.setItem("theme", "dark");
// Retrieve data
const theme = localStorage.getItem("theme"); // "dark"
// Remove data
localStorage.removeItem("theme");
// Clear all localStorage
localStorage.clear();
sessionStorage: Temporary and Tab-Specific// Save data
sessionStorage.setItem("formStep", "2");
// Retrieve data
const step = sessionStorage.getItem("formStep"); // "2"
// Remove data
sessionStorage.removeItem("formStep");
// Clear all sessionStorage
sessionStorage.clear();
Storage limits: ~5–10MB (varies by browser)
Strings only: You must stringify objects:
localStorage.setItem("user", JSON.stringify({ name: "Jane" }));
const user = JSON.parse(localStorage.getItem("user") || "{}");
Security: Data is visible to any JavaScript on the page. Do not store sensitive data like passwords or personal info.
| Question | Use |
|---|---|
| Should the data persist after the tab closes? | localStorage |
| Should the data be tied only to this tab session? | sessionStorage |
| Will the data be reused in another tab? | localStorage |
| Should the data reset on page reload or tab close? | sessionStorage |
To simplify usage, you can create utility functions:
function saveToStorage(key, value, persistent = true) {
const storage = persistent ? localStorage : sessionStorage;
storage.setItem(key, JSON.stringify(value));
}
function getFromStorage(key, persistent = true) {
const storage = persistent ? localStorage : sessionStorage;
const value = storage.getItem(key);
return value ? JSON.parse(value) : null;
}
localStorage and sessionStorage are essential tools in modern front-end development. While both provide client-side persistence, they differ in lifespan and scope. Understanding when and how to use each allows you to optimize your application's responsiveness, reduce server load, and enhance user experience.
By following best practices and being mindful of security limitations, these APIs can greatly enhance how your web app handles state and interactivity.