← All posts

localStorage vs sessionStorage vs cookies: where should you store data in the browser?

Lifetime, scope, security, what gets sent to the server: the real differences between localStorage, sessionStorage and cookies, what you should never put in them, and a small, robust JavaScript module to use them.

localStorage vs sessionStorage vs cookies: where should you store data in the browser?

Key points

  • localStorage and sessionStorage are for preferences and drafts; they’re never sent to the server.
  • A login token doesn’t belong in localStorage: an HttpOnly, Secure, SameSite cookie protects it far better against XSS.
  • Browser storage can vanish or be unavailable, so every read and write needs to handle failure.

Remembering a search filter, keeping a cart’s contents, noting that a user dismissed a banner, keeping a logged-in user signed in: sooner or later, every web project needs to store something in the browser. Three built-in mechanisms are available without a library, and they’re often used interchangeably. Yet the choice has real consequences for security, for how things behave across tabs and for what reaches the server on every request. Here’s how we decide on our projects.

The differences that actually matter

All three store text key-value pairs tied to the site’s origin (scheme, domain and port). What sets them apart:

  • localStorage: persists with no expiry date, shared across every tab on the same site, readable only from JavaScript, never sent to the server. Capacity is limited (a few megabytes, depending on the browser).
  • sessionStorage: same API, but scoped to a single tab. It survives a page reload and disappears when the tab closes. Two tabs open on the same page each get their own.
  • Cookies: small (about 4 KB each), with an expiry you choose, and above all sent automatically to the server with every request to the domain. The HttpOnly attribute can hide them from JavaScript entirely.

The practical rule that follows: if the server needs the information on every request (who is logged in), use a cookie. If only the interface needs it (a display setting, a draft), use localStorage or sessionStorage, and keep every request lean.

There’s a fourth option, IndexedDB, designed for large amounts of structured data and offline-capable apps. It’s asynchronous and more verbose; for preferences and small bits of state, it’s overkill.

localStorage and sessionStorage without the gotchas

The API is just four methods, but it has three traps that show up in plenty of production code. It only stores strings, so saving an object without JSON.stringify() gives you the string “[object Object]”. It can throw: quota exceeded, storage disabled by the user, or a restricted context such as some in-app browsers. And data outlives your deployments: if the format changes, returning visitors still have the old one.

We use a small module that handles all three at once, with a prefix to avoid clashing with third-party scripts and a version number to cleanly discard old formats:

// Small storage module: JSON, versioning, and no exceptions leaking out
const PREFIX = 'mysite:';
const VERSION = 2;

export function read(key, fallback = null) {
  try {
    const raw = localStorage.getItem(PREFIX + key);
    if (raw === null) return fallback;
    const { v, data } = JSON.parse(raw);
    return v === VERSION ? data : fallback; // old format: ignore it
  } catch {
    return fallback; // storage blocked, corrupted JSON…
  }
}

export function write(key, data) {
  try {
    localStorage.setItem(PREFIX + cle, JSON.stringify({ v: VERSION, data }));
    return true;
  } catch {
    return false; // quota exceeded or storage unavailable
  }
}

// Usage
write('filters', { category: 'shoes', sort: 'price' });
const filters = read('filters', { category: null, sort: 'relevance' });

When should you pick sessionStorage over localStorage? For anything tied to a task in progress in one specific tab: the current step of a multi-page form, the scroll position in a list before opening a detail page, state that would be confusing to find in another tab. For a lasting preference such as dark mode or language, localStorage is the right call.

One last point: these APIs are synchronous, so reading or writing large JSON strings blocks the main thread. For a few kilobytes it’s unnoticeable; if you’re storing lists of thousands of items, that’s your cue to move to IndexedDB.

What you should never put in localStorage

It’s a question we ask in every code review: is an authentication token stored in localStorage? The pattern is everywhere in single-page apps, and it has one major flaw: any script running on the page can read it. A single XSS hole, a compromised JavaScript dependency or a rogue third-party script is enough to exfiltrate the token and impersonate the user from anywhere.

An HttpOnly cookie can’t be read from JavaScript. An XSS flaw is still serious, but the attacker can’t walk away with the session:

// Server side (PHP): the session cookie is never readable from JavaScript
setcookie('session', $token, [
    'expires'  => time() + 60 * 60 * 24 * 14,
    'path'     => '/',
    'secure'   => true,     // HTTPS only
    'httponly' => true,     // hidden from document.cookie
    'samesite' => 'Lax',    // not sent on POST requests from other sites
]);
  • Secure: the cookie only travels over HTTPS.
  • SameSite=Lax: the cookie isn’t sent on POST requests started from another site, which already blocks a large share of CSRF attacks. For sensitive actions, an anti-CSRF token is still recommended.
  • Lifetime: short for a sensitive session, renewed on the server side; longer for a “remember me” option that can be revoked in the database.

More broadly, keep out any personal data that doesn’t need to be there: addresses, phone numbers, the contents of past orders. Local storage is readable by anyone using the same computer, and it isn’t cleared on logout unless you clear it yourself.

Syncing tabs and coping with disappearing data

When one tab changes localStorage, the other tabs on the same site receive a storage event. It’s a handy way to keep a cart counter or theme consistent everywhere, with no server call:

// Refresh the displayed cart when another tab changes it
window.addEventListener('storage', (e) => {
  if (e.key === 'mysite:cart') {
    showCount(read('cart', []).length);
  }
});

The tab that made the change doesn’t get the event, so it has to update its own display. sessionStorage, being per-tab, doesn’t fire anything elsewhere.

Finally, assume storage can disappear at any time. Users clear their data; private browsing wipes everything on close; Safari deletes script-written data for sites the user hasn’t visited in a week; a browser short on disk space may evict it. Our rule on projects is simple: nothing essential lives only in the browser. An important draft is also saved on the server, and a logged-in user’s cart is attached to their account.

FAQ

Do I need a consent banner to use localStorage?

European rules cover any storage of information on the user’s device, not just cookies. Storage strictly needed for the service the user asked for (a cart, a display preference they chose) is generally exempt; a tracking or analytics identifier isn’t. If in doubt, have your usage reviewed by whoever handles compliance.

Why doesn’t my localStorage data show up on a subdomain?

Storage is tied to the exact origin: www.example.com and shop.example.com each have their own, as do the HTTP and HTTPS versions. Only a cookie set with the Domain attribute can be shared across subdomains.

Can I encrypt what I put in localStorage?

You can, but the decryption key then has to live in the page’s JavaScript, where the same attacker can reach it. Client-side encryption doesn’t protect against XSS; the real protection is not storing sensitive data there in the first place.

Is your app keeping tokens or sensitive data in the browser? We audit and secure web and SaaS applications, from authentication to session handling.

Share LinkedIn Facebook X WhatsApp
</>

webtestudio

Web agency: custom WordPress sites, premium themes and SaaS software.

Discuss your project →