Skip to content
Tutorials Center
My learning

Topics

Lesson 94 of 156 ยท Browser APIs

localStorage and sessionStorage

Save data in the browser with localStorage and sessionStorage. Store objects as JSON, handle errors, expire old values and sync tabs with storage events.

A page forgets everything when it reloads. Variables, arrays and objects all live in memory and disappear the moment the user refreshes or closes the tab. Often that's fine. But some things should be remembered: a dark-mode choice, the contents of a half-written comment, the last filter a user picked, a list of recently viewed products.

The Web Storage API gives every website two small keyโ€“value stores in the browser: localStorage, which keeps data until it's deleted, and sessionStorage, which keeps data only for the current tab. Both are simple, synchronous and available in every browser. This lesson covers the API, storing real data as JSON, writing a safe wrapper, expiring old values and keeping several tabs in sync. The HTML course has a shorter introduction to Web Storage if you'd like a gentler first look.

Storage is disabled in these editors. For security, the examples on this site run in a sandbox with no storage of its own, so localStorage throws an error there. Code that must use real storage is shown read-only; copy it into a page on your own computer to try it. The live demos use a small in-memory stand-in with exactly the same methods, so everything you practice transfers directly.

The API in five methods

Both stores have the same interface. Keys and values are always strings:

JavaScript
localStorage.setItem("theme", "dark");     // add or overwrite
localStorage.getItem("theme");             // "dark"
localStorage.getItem("missing");           // null (not undefined)
localStorage.removeItem("theme");          // delete one key
localStorage.clear();                      // delete everything for this site

localStorage.length;                       // number of keys
localStorage.key(0);                       // the name of the first key

You may also see property syntax such as localStorage.theme = "dark". It works, but avoid it: a key called length or getItem would collide with the built-in members. Stick to the methods.

Data is stored per origin: https://shop.example.com can't read what https://blog.example.com saved, and the http:// and https:// versions of a site are separate too.

localStorage vs sessionStorage

localStorage sessionStorage
Lifetime Until deleted by code or the user Until the tab is closed
Shared between tabs Yes, across all tabs of the origin No, each tab has its own
Survives a reload Yes Yes
Typical use Preferences, saved drafts, caches Multi-step form progress, one-time state

Feature detection and the sandbox

Storage can be unavailable even in modern browsers: in sandboxed frames like ours, with some privacy settings, or when the browser blocks storage for a site. Even reading the localStorage property can throw. Always wrap first access in try...catch:

JS Is storage available here?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The probe also catches a full store, because setItem() throws a QuotaExceededError when there is no room left.

An in-memory stand-in

Because the sandbox has no storage, here is a tiny class with the same five methods. It keeps everything in a Map and, like the real thing, turns every key and value into a string. The real objects behave the same way, except that their data survives reloads:

JS Everything becomes a string

Press Run (or Ctrl + Enter) to see the console output here.

No output.

These are the classic storage bugs. A number comes back as a string, so + 1 concatenates. false comes back as "false", which is truthy. An object becomes the useless "[object Object]". The fix is to convert values deliberately, and for anything structured that means JSON.

Storing objects as JSON

JSON.stringify() turns objects, arrays, numbers and booleans into a string, and JSON.parse() turns them back. Reading needs two safety nets: the key might not exist (getItem() returns null), and the stored text might not be valid JSON, perhaps written by an older version of your code or edited by hand in DevTools.

JS Safe JSON helpers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Remember JSON's limits: Date objects come back as strings, Map, Set and class instances become plain objects, and undefined values disappear. Store dates as timestamps or ISO strings and rebuild them after loading.

Remembering preferences on a page

This page lets you pick a theme and type a draft note. On a real website it would use localStorage and remember both across reloads. Here, the try...catch falls back to the in-memory stand-in, so everything works until you press Run again:

Theme and draft that persist

Two habits are worth copying. Keys use a prefix (prefs.) so your data doesn't clash with other scripts on the same origin. And state is restored before the user sees the page, so there's no flash of the wrong theme.

Expiring and versioning data

Web Storage has no built-in expiry. If you use it as a cache, store a timestamp with the value and ignore anything too old. Adding a version number lets you discard data saved in an old format after you change your app:

JavaScript
const CACHE_VERSION = 2;

function saveCached(key, value, maxAgeMs) {
  const entry = { v: CACHE_VERSION, expires: Date.now() + maxAgeMs, value };
  localStorage.setItem(key, JSON.stringify(entry));
}

function loadCached(key) {
  try {
    const entry = JSON.parse(localStorage.getItem(key));
    if (entry?.v === CACHE_VERSION && Date.now() < entry.expires) {
      return entry.value;
    }
  } catch {
    // corrupted entry: fall through
  }
  localStorage.removeItem(key);
  return null;
}

saveCached("weather.oslo", { temp: 4, sky: "cloudy" }, 10 * 60 * 1000); // 10 minutes

Note that JSON.parse(null) returns null, so a missing key simply leads to entry?.v being undefined and the function returning null.

Syncing tabs with the storage event

When one tab changes localStorage, every other tab of the same origin receives a storage event on window. The tab that made the change doesn't get the event. This lets you keep tabs in sync, for example logging out everywhere at once or updating a cart badge:

JavaScript
window.addEventListener("storage", (event) => {
  console.log(event.key);      // which key changed (null after clear())
  console.log(event.oldValue); // previous value, or null
  console.log(event.newValue); // new value, or null if removed
  console.log(event.storageArea === localStorage); // true

  if (event.key === "prefs.dark") {
    document.body.classList.toggle("dark", event.newValue === "true");
  }
});

To try it locally, open the same page in two tabs and change the setting in one; the other updates instantly. sessionStorage changes don't reach other tabs, since each tab has its own session store. For richer cross-tab messaging, look at BroadcastChannel.

Limits and good practice

  • Size: browsers allow roughly 5 MB per origin for localStorage (the exact limit varies). Plan for QuotaExceededError.
  • Synchronous: every call blocks the main thread while the browser reads or writes. Fine for small values, bad for megabytes of data in a loop. For large or structured data, use IndexedDB.
  • No secrets. Any script running on your page can read storage, including injected malicious code. Never store passwords, and think carefully before storing access tokens there. Servers usually prefer HttpOnly cookies for sessions, because JavaScript can't read them.
  • Users can clear it. Private browsing, "clear site data" and storage pressure can wipe it. Treat storage as a convenience, never as the only copy of important data.
  • Strings only. Convert deliberately with JSON.stringify()/JSON.parse() or String()/Number().

Cookies, localStorage or sessionStorage?

The browser gives you three places to keep small pieces of data. They look similar but behave very differently, and picking the wrong one causes bugs and security holes.

Cookie localStorage sessionStorage
Lifetime Until Expires/Max-Age, or when the browser closes (a "session cookie") Until your code or the user deletes it Until the tab is closed (survives reloads)
Scope The site, optionally limited by Domain and Path One origin (scheme + host + port) One origin in one tab
Sent to the server Automatically, on every matching request Never Never
Size About 4 KB each About 5 MB per origin About 5 MB per origin
Readable by JavaScript Yes, unless the cookie is HttpOnly Always Always
API document.cookie (awkward text string) getItem / setItem getItem / setItem
Typical use Login sessions, anything the server must see Preferences, drafts, cached data Wizard progress, one-tab state

Use this as a quick decision guide:

  • The server needs it on every request (a login session, a language the server renders): use a cookie, ideally set by the server with HttpOnly, Secure and SameSite. See Cookies.
  • Only your JavaScript needs it and it should last: use localStorage. Examples are theme, filters and saved drafts.
  • It belongs to this tab and should vanish afterwards: use sessionStorage. Examples are a half-completed checkout step or a scroll position.
  • It's large, structured or searchable: use IndexedDB instead of any of these three.

What can go wrong

Each choice has a different weakness:

  • Anything JavaScript can read can be stolen by cross-site scripting (XSS). If an attacker gets one script to run on your page, it can read all of localStorage, sessionStorage and every cookie that isn't HttpOnly. Read XSS, CSRF and Safe DOM Updates for how that happens.
  • Cookies are sent automatically, which is what makes cross-site request forgery (CSRF) possible: another site can trigger a request that carries your cookie. SameSite=Lax or Strict blocks most of that. Web Storage is never sent automatically, so it isn't affected by CSRF, but your own code has to attach the data to every request that needs it.
  • Storage is per origin: http://example.com and https://example.com have separate storage, and so do example.com and app.example.com. Cookies can be shared across subdomains with a Domain attribute.
  • Privacy rules apply to all three if they track people. See the note in Cookies.

JWT basics: what a token is and where to keep it

Many login systems issue a JSON Web Token (JWT). It's a signed piece of text that says who you are, which the client sends back with each request. You'll see JWTs whenever you work with APIs, so it helps to know exactly what one is, and what it is not.

A JWT has three parts separated by dots:

TEXT
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 . eyJzdWIiOiJ1c2VyLTQyIiwi... . u_yhHBh2afL-ey3Rc...
          header                               payload                      signature
  1. The header says how the token is signed, for example {"alg": "HS256", "typ": "JWT"}.
  2. The payload holds claims: facts such as sub (the user id), iat (issued at), exp (expires at, in seconds since 1970) and any custom fields like a role.
  3. The signature is a hash of the first two parts made with a secret key that only the server knows.

The header and payload are JSON encoded as base64url (base64 with - and _ instead of + and /, and no = padding), so they travel safely inside URLs and HTTP headers.

Encoded is not encrypted. Anyone holding a JWT can read the payload, as the demo below shows. Never put passwords, personal secrets or anything private in it. The signature doesn't hide the data. It only proves that nobody changed it.

The signature is the entire point. If someone edits the payload (say, changing role to admin), the signature no longer matches, and a server that checks it rejects the token. Only a server (or any party holding the secret) can verify it. JavaScript in the browser can decode a token to display the user's name or check the expiry for convenience, but it must never be trusted for security decisions, because an attacker controls the browser.

The demo signs a token with HMAC-SHA-256 using the Web Crypto API, reads it back without any secret, and then shows three ways verification fails.

JS Sign, decode and verify a JWT

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A few things to notice. The payload decodes to readable JSON without any key. Changing one character (reader to admin) makes the signature check fail, and so does using the wrong secret. And exp is checked separately after the signature: a perfectly valid signature on an expired token must still be refused. Production code should use a well-tested library for this (such as jose), which also handles key formats, asymmetric algorithms such as RS256 and constant-time comparison.

Where should the token live in the browser?

There's no perfect answer, only trade-offs:

Where Good Bad
localStorage / sessionStorage Simple, survives reloads, no CSRF risk Any injected script can read and steal the token (XSS)
HttpOnly cookie JavaScript can't read it, so XSS can't steal it directly Sent automatically, so you need SameSite and often CSRF protection
In memory (a JavaScript variable) Hardest to steal after the page is gone Lost on reload, so you need a way to get a new token

A widely recommended pattern for browser apps is a short-lived access token (minutes) kept in memory, plus a refresh token in an HttpOnly, Secure, SameSite cookie that the server uses to issue new access tokens. Whatever you choose, keep tokens short-lived, serve everything over HTTPS, and fix XSS bugs first, because they make every browser storage option unsafe. For a deeper look at these defenses, see Security.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does localStorage.getItem("nope") return when the key doesn't exist?

    getItem() returns null for missing keys, which is why ?? fallback works well with it.
  2. 2. You run localStorage.setItem("count", 5) and later localStorage.getItem("count") + 1. What is the result?

    Storage converts values to strings, so you get "5" and then string concatenation. Use Number() when reading.
  3. 3. Which statement about sessionStorage is true?

    sessionStorage is scoped to a single tab and survives reloads, but not closing the tab.
  4. 4. Tab A calls localStorage.setItem("theme", "dark"). Which tabs receive a storage event?

    The event notifies other same-origin tabs about a change; the tab that made the change doesn't receive it.
  5. 5. Why should you avoid putting secrets such as passwords in localStorage?

    Storage is fully readable by JavaScript on the origin, including injected code, so it's no place for secrets.

Summary

  • localStorage persists until deleted; sessionStorage lasts for one tab. Both are per origin.
  • Use setItem, getItem (returns null when missing), removeItem, clear, key and length.
  • Everything is stored as a string: use JSON for objects and convert numbers and booleans when reading.
  • Wrap storage access in try...catch: it can be blocked, full or hold corrupted data.
  • Add prefixes, versions and timestamps to keep stored data tidy and fresh.
  • The storage event keeps other tabs in sync; never store secrets in Web Storage.
  • Cookies are sent to the server and can be HttpOnly; Web Storage stays in the browser and is always readable by scripts. Pick by who needs the data and how long it should last.
  • A JWT is signed, not encrypted: anyone can read its payload, and only the server may trust it after checking the signature and exp.

Next: Cookies.