Lesson 10 of 12 · 12 min · How the browser works

Cookies and browser storage

Covers: Current browser behaviour (Chromium, Firefox, Safari). Updated 13 Nov 2026. Part of the Frontend Developer roadmap.

What you will learn

  • What cookies are, how they are sent, and the HttpOnly, Secure, SameSite, Domain, Path and expiry attributes
  • localStorage, sessionStorage, IndexedDB and the Cache API: differences and limits
  • How to choose the right storage for a task
  • Where to keep session identifiers and tokens safely
  • Privacy, consent and the common mistakes

In simple words

Web pages forget everything between requests unless someone writes it down. The browser has several notebooks: cookies, which travel automatically to the server with every request (how you stay logged in); small browser-only shelves such as localStorage for preferences; and a proper filing cabinet, IndexedDB, for larger data. Choosing the right one matters for both speed and security, because anything stored where scripts can read it can also be stolen by a malicious script.

Words to know

  • Cookie: a small piece of data a server asks the browser to store and send back with later requests.
  • Origin: the combination of scheme, host and port, such as https://example.com:443.
  • Session: the period during which a user is logged in or active.
  • XSS: cross-site scripting, an attack where malicious script runs inside your page.

Cookies

A cookie is created by a server with a Set-Cookie response header, or by JavaScript with document.cookie. The browser then sends it back in the Cookie request header with every request to the matching site, which is why cookies carry login sessions.

HTTP/2 200
Set-Cookie: session=abc123; Max-Age=3600; Path=/; Secure; HttpOnly; SameSite=Lax

GET /orders HTTP/2
Cookie: session=abc123
Attribute Meaning
Max-Age / Expires lifetime. Without them it is a session cookie removed when the browser session ends
Domain which hosts get the cookie (omit it to restrict to the exact host; setting example.com includes subdomains)
Path the URL path prefix it is sent to
Secure only sent over HTTPS
HttpOnly not accessible to JavaScript (document.cookie), which protects session ids from XSS theft
SameSite when the cookie is sent on cross-site requests: Strict (never), Lax (only for top-level navigations such as clicking a link; the default in modern browsers), None (always, but requires Secure)
Partitioned stores a third-party cookie separately per top-level site (CHIPS)

Security recommendations for a login cookie: Secure; HttpOnly; SameSite=Lax (or Strict), a short and sensible lifetime, a random unguessable value (or a signed token), and a name with the __Host- prefix (__Host-session), which forces Secure, Path=/ and no Domain. SameSite reduces CSRF risk. Frameworks (Spring Security, Express session) set most of this for you; verify the headers in DevTools (Application tab, Cookies).

Limits: about 4 KB per cookie and around 50 to 180 cookies per domain depending on the browser; and every cookie is sent with every request, so large cookies slow every call. Do not store data in cookies that the server can look up from a session id.

First-party and third-party cookies: a first-party cookie belongs to the site you are visiting; a third-party cookie belongs to another domain embedded in the page (ads, analytics, social widgets) and enables cross-site tracking. Browsers are restricting third-party cookies in different ways (Safari and Firefox block them by default; Chrome has changed its plans more than once), so do not build features that depend on them; check the current status on MDN.

localStorage and sessionStorage

The Web Storage API stores key-value strings in the browser:

localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme");        // "dark" or null
localStorage.removeItem("theme");

localStorage.setItem("draft", JSON.stringify({ title: "Notes", words: 120 }));
const draft = JSON.parse(localStorage.getItem("draft") ?? "null");

sessionStorage.setItem("step", "2");                 // gone when the tab closes
localStorage sessionStorage
Lifetime until cleared by the user or the site until the tab or window is closed
Scope per origin, shared across tabs per origin and per tab
Size about 5 MB per origin (varies) about 5 MB
Sent to the server never never

Properties and cautions:

  • Synchronous: reads and writes block the main thread, so avoid big data and frequent writes.
  • Strings only: serialise with JSON.stringify, and expect getItem to return null.
  • Readable by any script on the page, including injected malicious scripts: never store session tokens, passwords or personal data in localStorage if you can avoid it. It suits harmless preferences (theme, language, a dismissed banner) and drafts.
  • It can throw (storage full, blocked in private modes or by privacy settings), so wrap in try/catch.
  • The storage event fires in other tabs when a value changes, useful for syncing logout across tabs.
  • It is not available in Web Workers or service workers (use IndexedDB there).

IndexedDB

A proper client-side database for large amounts of structured data: objects, files and blobs, with indexes, transactions and asynchronous access. Typical uses: offline apps, caching API results, drafts of large documents, media. Its API is verbose, so most people use a small wrapper such as idb, Dexie or localForage.

// with the idb library
const db = await openDB("shop", 1, {
  upgrade(db) { db.createObjectStore("orders", { keyPath: "id" }); },
});
await db.put("orders", { id: 101, amount: 1200 });
const order = await db.get("orders", 101);

Storage is far larger (a share of free disk space, often hundreds of MB and more), but the browser may evict it under storage pressure unless the site requests persistence (navigator.storage.persist()). Like Web Storage, it is per origin and readable by scripts on the page.

Cache API and service workers

The Cache API stores HTTP responses (request and response pairs), controlled by JavaScript, mainly from a service worker that intercepts network requests. It enables offline support and instant repeat loads (a progressive web app, PWA): cache the app shell (HTML, CSS, JS, icons), serve it first, and update in the background. It is separate from the browser's automatic HTTP cache, which follows the server's Cache-Control headers.

Choosing storage

Need Use
keep a user logged in an HttpOnly, Secure, SameSite session cookie set by the server
a small preference (theme, language) localStorage (or a cookie if the server needs it)
state for one tab (a wizard step) sessionStorage
large, structured or offline data IndexedDB
offline pages and assets Cache API with a service worker
shareable state (filters, page, sort) the URL (query string), so people can bookmark and share
data the server needs on each request cookie (small) or a header
data that must be reliable and shared across devices the server and a database, not the browser
in-memory temporary state JavaScript variables, component state

Browser storage is not secure and not permanent: users can clear it, edit it in DevTools and lose it on a new device. Never trust values read back from it for security decisions; validate on the server.

Where to keep tokens

For a login in a web app, the safest common choice is an HttpOnly; Secure; SameSite cookie holding a session id or token, because JavaScript (and therefore XSS) cannot read it. The cost is that cookies are sent automatically, so you need CSRF protection (SameSite and anti-forgery tokens). A token in localStorage is easy to use with Authorization headers and is not sent automatically (no CSRF), but any XSS can steal it. Neither is perfect: prevent XSS (escape output, a strict Content Security Policy, avoid innerHTML with untrusted data, keep dependencies updated), use short-lived access tokens with refresh tokens, and use a standard identity provider rather than inventing your own. Mobile and single-page apps often use a "backend for frontend" that keeps tokens server-side and gives the browser only a session cookie.

DevTools

Open Application (Chrome, Edge) or Storage (Firefox): see and edit Cookies, Local storage, Session storage, IndexedDB, Cache storage and Service workers, check the attributes of each cookie, and clear site data to test a fresh visit.

Common mistakes

  • Storing session tokens or personal data in localStorage.
  • Session cookies without HttpOnly, Secure or SameSite.
  • Large cookies that slow every request.
  • Trusting data read from browser storage for security decisions.
  • Heavy synchronous localStorage use on the main thread.
  • Not handling storage errors in private mode or when quota is full.
  • Depending on third-party cookies.

Try it yourself

  1. Log in to a test site and inspect its session cookie in DevTools: which attributes are set?
  2. Store a theme preference in localStorage and read it on page load; handle a failure with try/catch.
  3. Use sessionStorage for a wizard step and show that a new tab starts fresh.
  4. Write a short note on where you would store: a login session, a draft essay, a dark-mode choice and a list of recent searches.
  5. Open the Application panel on three popular sites and list the storage each uses.

Check yourself

What does the HttpOnly cookie attribute do?

It stops JavaScript from reading the cookie through document.cookie, protecting session ids from theft by XSS.

What is the difference between localStorage and sessionStorage?

localStorage persists until cleared and is shared across tabs of an origin; sessionStorage lasts only for one tab or window session and is not shared.

When is a cookie sent to the server?

With every request to the cookie's matching domain and path, subject to Secure and SameSite rules.

Why is localStorage a poor place for authentication tokens?

Any script running on the page, including injected malicious scripts, can read it, so an XSS flaw exposes the token.

Interview questions

Cookies versus localStorage versus sessionStorage: when would you use each?

Cookies when the server needs the value on each request, especially login sessions (with HttpOnly, Secure, SameSite); localStorage for non-sensitive preferences that persist; sessionStorage for per-tab temporary state.

What does SameSite do and what are its values?

It controls whether a cookie is sent on cross-site requests: Strict never, Lax only on top-level navigations (the default), None always but requiring Secure. It mitigates CSRF.

How would you store large amounts of data in the browser?

In IndexedDB, asynchronously and per origin, with a wrapper library; the Cache API for HTTP responses in a service worker; remembering that the browser can evict data.

Summary

  • Cookies travel to the server automatically; protect them with Secure, HttpOnly and SameSite.
  • localStorage and sessionStorage hold small strings readable by scripts; use them for harmless preferences.
  • IndexedDB and the Cache API handle large and offline data.
  • Do not keep secrets in script-readable storage, do not trust it, and consider privacy and consent.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on HTML, CSS and how the web works for Frontend Developer and scores every answer, with what to fix.