Skip to the content

Lesson 90 of 296

Cookies vs localStorage vs sessionStorage

What you will learn

  • The ways a browser can store data
  • How each one works and its limits
  • Cookie attributes and what they protect
  • Security: where to store login tokens
  • IndexedDB for larger data
On this page

The options

CookieslocalStoragesessionStorageIndexedDB
Size limit (approx.)About 4 KB per cookieAbout 5 MB per origin (varies by browser)About 5 MB per originMuch larger, based on disk space
Lasts untilThe expiry date, or the browser session endsDeleted by code or the userThe tab is closedDeleted by code or the user
Shared between tabsYesYes (same origin)No, one tab onlyYes
Sent to the server automaticallyYes, with every matching requestNoNoNo
Readable by JavaScriptYes, unless HttpOnlyYesYesYes
APIdocument.cookie (awkward), or set by the serverSimple, synchronousSimple, synchronousAsynchronous, more complex
Data typeStringsStringsStringsStructured data, files

localStorage

localStorage.setItem("theme", "dark");
localStorage.getItem("theme");          "dark"
localStorage.getItem("missing");        null
localStorage.removeItem("theme");
localStorage.clear();

It only stores strings. Store objects as JSON:

const prefs = { theme: "dark", fontSize: 16 };
localStorage.setItem("prefs", JSON.stringify(prefs));
const saved = JSON.parse(localStorage.getItem("prefs") ?? "{}");

Without JSON.stringify, an object is saved as the useless string "[object Object]".

Wrap it in try...catch: it can throw when storage is full, disabled, or in some private browsing modes, and JSON.parse throws on corrupted data.

function loadPrefs() {
  try {
    return JSON.parse(localStorage.getItem("prefs")) ?? {};
  } catch {
    return {};
  }
}

It is synchronous: it blocks the main thread while reading and writing. Keep the data small.

Good uses: theme, language, dismissed banners, unsaved drafts, small UI preferences.

sessionStorage

Same methods as localStorage, but the data belongs to one tab and is deleted when that tab closes. Each new tab starts empty.

Good uses: a multi-step form in progress, a scroll position to restore within that tab.

The storage event

When localStorage changes in another tab of the same site, the other tabs receive a storage event. Use it to keep tabs in sync, for example logging out everywhere:

window.addEventListener("storage", (e) => {
  if (e.key === "loggedOut") showLoginScreen();
});

Cookies

A cookie is a small piece of data the browser stores and sends back to the server with every request to that domain. Cookies are mainly for the server: sessions, login state, tracking.

A server sets a cookie with a response header:

Set-Cookie: sessionId=abc123; Max-Age=86400; Path=/; Secure; HttpOnly; SameSite=Lax
AttributeMeaning
Expires / Max-AgeWhen it expires. Without them, it is a session cookie, removed when the browser closes.
Domain / PathWhich URLs it is sent to
SecureOnly sent over HTTPS
HttpOnlyJavaScript cannot read it (document.cookie will not show it). Protects against XSS stealing it.
SameSite=StrictNever sent with requests that come from other sites
SameSite=LaxSent when the user navigates to your site from a link, but not with most cross-site requests. The default in modern browsers.
SameSite=NoneSent with cross-site requests; must also be Secure

SameSite helps protect against CSRF (Cross-Site Request Forgery), where another site tricks the user's browser into sending a request to your site (Part 20).

Cookies from JavaScript

document.cookie = "banner=hidden; Max-Age=2592000; Path=/; SameSite=Lax";
document.cookie;          "banner=hidden; other=value"

The API is awkward: setting adds or updates one cookie; reading returns all cookies (except HttpOnly ones) as one string. Most code uses a small library or lets the server manage cookies.

Cookies are sent with every request to their domain, including images and scripts. Large or many cookies slow down every request. Do not store data in cookies that the server does not need.

Where to store login tokens: the security question

This is one of the most common front end security questions.

PlaceRisk
localStorage / sessionStorageAny JavaScript on the page can read it. If an attacker achieves XSS (Lesson 87), they can steal the token and use it anywhere.
HttpOnly, Secure, SameSite cookieJavaScript cannot read it, so XSS cannot steal it directly. Needs CSRF protection, which SameSite and CSRF tokens provide.
Memory (a JavaScript variable)Lost on page refresh; often combined with a refresh token in an HttpOnly cookie

The usual recommendation: keep session identifiers and refresh tokens in HttpOnly, Secure, SameSite cookies, and never put long-lived secrets in localStorage. Part 15 covers sessions, JWTs and refresh tokens in detail.

Even with HttpOnly cookies, XSS is still dangerous: the attacker's script can make requests as the user while the page is open. Preventing XSS is always the first defence.

IndexedDB

IndexedDB is a real database inside the browser: asynchronous, large capacity, stores objects, files and indexes. Used for offline apps, caching large data and storing files. Its API is complicated, so most people use a small wrapper library (such as idb).

The Cache Storage API (used with Service Workers) stores whole HTTP responses for offline support.

Privacy and the law

In the UK and EU, cookies and similar storage that are not strictly necessary (analytics, advertising) need the user's consent (UK PECR and GDPR rules). Cookies needed for the site to work, like login sessions and shopping baskets, do not need consent. This affects how you build cookie banners.

Common mistakes

  • Storing objects in localStorage without JSON.
  • Storing access tokens or other secrets in localStorage.
  • Not handling null from getItem, or invalid JSON.
  • Large cookies sent with every request.
  • Forgetting Secure and HttpOnly on session cookies.
  • Expecting sessionStorage to be shared between tabs.

How to say it in an interview

"Cookies are small, sent automatically with every request to their domain, and can be HttpOnly so JavaScript cannot read them, plus Secure and SameSite for HTTPS-only and CSRF protection. localStorage holds about 5 megabytes of strings per origin, persists until cleared and is shared across tabs; sessionStorage is the same but per tab and cleared when the tab closes. Both are synchronous and readable by any script, so an XSS attack can steal anything there. I keep session and refresh tokens in HttpOnly Secure SameSite cookies, use localStorage only for non-sensitive preferences, and IndexedDB for large or offline data."

Key words

WordMeaning
CookieSmall data sent to the server with every request
localStoragePersistent key-value storage in the browser
sessionStorageKey-value storage for one tab
IndexedDBAn asynchronous database in the browser
HttpOnlyA cookie flag that hides it from JavaScript
SecureA cookie flag: HTTPS only
SameSiteA cookie setting that controls cross-site sending
CSRFTricking a browser into sending an unwanted request to another site
OriginProtocol + domain + port

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.