Script Valley
JavaScript: The Complete Language
DOM Manipulation and Browser APIsLesson 5.3

Local Storage and Session Storage in JavaScript

localStorage API, sessionStorage API, setItem getItem removeItem clear, JSON serialization, storage limits, storage events, when to use each, security considerations

Client-Side Persistent Storage

localStorage and sessionStorage store key-value string pairs in the browser without needing a server. Both expose the same API. The critical difference: localStorage persists indefinitely until explicitly cleared; sessionStorage is erased automatically when the browser tab or window closes. Both are scoped to the page's origin — one origin cannot read another's storage.

Basic API

// write
localStorage.setItem("theme", "dark");

// read — returns null if the key does not exist
const theme = localStorage.getItem("theme"); // "dark"

// delete one key
localStorage.removeItem("theme");

// delete all keys for this origin
localStorage.clear();

Storing Objects — Must Serialize to JSON

const user = { name: "Ana", role: "admin" };
localStorage.setItem("user", JSON.stringify(user));

// Always parse on read — returns a string otherwise
const loaded = JSON.parse(localStorage.getItem("user"));
loaded.name; // "Ana"

Storage Event — Cross-Tab Communication

window.addEventListener("storage", (e) => {
  if (e.key === "theme") {
    applyTheme(e.newValue);
  }
});
// Fires in OTHER open tabs when localStorage changes in this tab

Limits and Security

Storage is limited to roughly 5MB per origin. Never store authentication tokens or sensitive data in localStorage — any JavaScript on the same origin can read it, making it vulnerable to XSS attacks. Use HTTP-only cookies for tokens: the browser sends them automatically and JavaScript cannot access them at all.

Up next

The Intersection Observer and Mutation Observer APIs

Sign in to track progress