Skip to content
HTML5

Local & Session Storage

Persist data in the browser with the Web Storage API.

By EZ4Code Team
storageweb-storage

Code

// Store a value (strings only; serialize objects)
localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme");   // "dark"

// Objects need JSON
const user = { name: "Alice", age: 30 };
localStorage.setItem("user", JSON.stringify(user));
const restored = JSON.parse(localStorage.getItem("user"));

// Remove one key or everything
localStorage.removeItem("theme");
localStorage.clear();

// Listen for changes in other tabs
window.addEventListener("storage", e => {
  console.log(e.key, "changed from", e.oldValue, "to", e.newValue);
});

// Session storage clears when the tab closes
sessionStorage.setItem("token", "abc");

Explanation

localStorage persists string key-value pairs with no expiration, while sessionStorage clears when the tab closes. Both share a synchronous API of setItem, getItem, and removeItem. The storage event fires in other tabs when data changes, enabling lightweight cross-tab sync.

More HTML5 Snippets