HTML APIs

LocalStorage and SessionStorage Web Storage APIs

The Web Storage API gives web pages a simple key-value store in the browser through two objects: localStorage (persists indefinitely) and sessionStorage (cleared when the tab closes).


What is Web Storage?

Web Storage is an HTML5 API for storing string key-value pairs in the browser, scoped to a single origin (protocol + host + port). It replaced the old habit of stuffing small data into cookies. It comes in two flavours that share the same methods but differ in lifetime and scope: window.localStorage and window.sessionStorage.

localStorage vs sessionStorage

localStorage keeps data until the code (or the user) explicitly deletes it - it survives tab closes, browser restarts and reboots, and is shared across all tabs of the same origin. sessionStorage is isolated to a single tab and is wiped the moment that tab or window is closed.

FeaturelocalStoragesessionStorage
LifetimeUntil deleted (persistent)Until the tab/window closes
ScopeShared across all tabs of the originOnly the tab that created it
Survives restartYesNo
Typical useUser preferences, theme, cached dataMulti-step form state, one-visit data

The four core methods

Both objects expose the same interface: setItem, getItem, removeItem, clear, plus the key(index) and length helpers to iterate stored items.

Basic Web Storage operations
// Save a value
localStorage.setItem("theme", "dark");

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

// Remove a single key
localStorage.removeItem("theme");

// Wipe everything for this origin
localStorage.clear();

// Iterate all keys
for (let i = 0; i < localStorage.length; i++) {
  const key = localStorage.key(i);
  console.log(key, localStorage.getItem(key));
}

// sessionStorage uses the exact same API
sessionStorage.setItem("step", "2");

Storing objects with JSON

Web Storage can only hold strings. To store objects or arrays, serialise them with JSON.stringify() when saving and JSON.parse() when reading. Anything non-string you pass is silently coerced to a string, which is why raw objects become the useless "[object Object]".

Persisting an object as JSON
const user = { name: "Aditi", role: "intern", darkMode: true };

// Save: serialise to a JSON string
localStorage.setItem("user", JSON.stringify(user));

// Load: parse back into an object
const saved = JSON.parse(localStorage.getItem("user"));
console.log(saved.name); // "Aditi"

// Guard against missing / corrupt data
let prefs;
try {
  prefs = JSON.parse(localStorage.getItem("prefs")) || {};
} catch {
  prefs = {};
}
ℹ️

Capacity is roughly 5 MB per origin (some browsers allow up to 10 MB). Exceeding the quota throws a QuotaExceededError, so wrap large writes in try/catch. Data is stored as UTF-16, so each character can count as 2 bytes toward the limit.

⚠️

Web Storage is synchronous and readable by any script on the page. Never store passwords, tokens or sensitive personal data in it - it is vulnerable to XSS. Also note it is not sent to the server automatically, unlike cookies.

Web Storage vs Cookies

AspectWeb StorageCookies
Capacity~5 MB per origin~4 KB per cookie
Sent to serverNo, stays in the browserYes, on every HTTP request
ExpirylocalStorage never; sessionStorage on tab closeConfigurable via Expires/Max-Age
AccessJavaScript onlyJavaScript + server (unless HttpOnly)
Best forClient-side state and cachingAuth/session identifiers, server-read data
💡

Listen for the 'storage' event on window to react when localStorage changes in another tab of the same origin - useful for keeping multiple tabs in sync (e.g. logging out everywhere at once).

Ready to use your HTML skills?

Find web development internships and fresher jobs across India.

Browse Web Dev Internships