Lesson 10 of 12 · 12 min · How the browser works
Cookies and browser storage
What you will learn
- What cookies are, how they are sent, and the
HttpOnly,Secure,SameSite,Domain,Pathand 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.
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 expectgetItemto returnnull. - Readable by any script on the page, including injected malicious scripts: never store session tokens, passwords or personal data in
localStorageif 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
storageevent 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,SecureorSameSite. - Large cookies that slow every request.
- Trusting data read from browser storage for security decisions.
- Heavy synchronous
localStorageuse on the main thread. - Not handling storage errors in private mode or when quota is full.
- Depending on third-party cookies.
Try it yourself
- Log in to a test site and inspect its session cookie in DevTools: which attributes are set?
- Store a theme preference in
localStorageand read it on page load; handle a failure withtry/catch. - Use
sessionStoragefor a wizard step and show that a new tab starts fresh. - 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.
- 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,HttpOnlyandSameSite. localStorageandsessionStoragehold 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
- MDN: Using HTTP cookies: attributes, security and the
Set-Cookieheader. - MDN: Web Storage API:
localStorageandsessionStorage. - MDN: Storage quotas and eviction criteria: limits and persistence.
- OWASP: Session Management Cheat Sheet: secure session cookies.
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.