Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 20 min · revision 2

Where Browser Data Lives: Cookies, Storage, IndexedDB and Caches

Compare the four places a browser can keep data on the device — cookies, Web Storage, IndexedDB and the Cache API — by capacity, lifetime, access style and exposure, and store structured notes in IndexedDB.

Contentsand lesson path

What you will learn

  • Choose between cookies, Web Storage, IndexedDB and the Cache API by capacity, persistence, synchronous or asynchronous access and exposure to scripts, and persist structured app data in IndexedDB.

Prerequisites: Async JavaScript & Fetch

01. Why it matters

A web page starts every visit with an empty memory. Everything that survives a reload — a signed-in session, a saved draft, notes written offline, the app shell that renders without a network — lives in one of four stores the browser provides: cookies, Web Storage, IndexedDB and the Cache API. They differ in capacity, lifetime, how you read and write them, and who else can read them.

Choosing the wrong one is not a style mistake; it produces concrete failures. A catalogue of thousands of records crammed into localStorage and parsed on every keystroke makes typing stutter, because each read and parse runs synchronously on the main thread. Session tokens in Web Storage are one XSS away from theft. Cached Response objects cannot be queried by field, however much the code wishes they were records.

This lesson compares the four stores on the dimensions that drive the choice, runs one note through all of them, and looks at quotas, eviction and exposure to scripts. The lab at the end of the skill builds on exactly this decision.

02. The four stores

All four are keyed by origin (scheme plus host plus port): data saved by https://notes.example is invisible to https://other.example. Within an origin they behave very differently.

  • Cookies are name and value pairs the browser attaches to matching HTTP requests. They are the only store the server writes (Set-Cookie) and reads on every request, which makes them the natural home for session identifiers. Individual cookies are small (a few kilobytes), and attributes such as HttpOnly, Secure and SameSite control who may read and send them.
  • Web Storage — localStorage and sessionStorage — is a synchronous map of strings. Same API, different lifetime: localStorage persists until the user or the code clears it, sessionStorage dies with the tab. Values are strings only, capped at roughly 5 MB per origin.
  • IndexedDB is a transactional database of structured objects with indexes for queries. Access is asynchronous and promise-friendly (with a wrapper), capacity is large — hundreds of megabytes or more — and records keep their JavaScript types through structured clone.
  • The Cache API stores Request and Response pairs, one per URL. It is built for HTTP traffic — app shells, assets, API GET responses — and is the store behind offline web apps, which the later lesson Installable and Offline covers in full.
JavaScript · one note in all four stores
const log = (label, value) => console.log(label + ': ' + value);

// 1. localStorage: synchronous, string keys and values only
localStorage.setItem(
  'note:1',
  JSON.stringify({ id: 1, text: 'buy milk', tags: ['home'] }),
);
log('localStorage raw', localStorage.getItem('note:1'));

// 2. sessionStorage: same API, lifetime of the tab
sessionStorage.setItem('draft', 'half-written note');
log('sessionStorage', sessionStorage.getItem('draft'));

// 3. cookies: pairs, visible to document.cookie unless HttpOnly
document.cookie = 'theme=dark; path=/; SameSite=Lax';
log('document.cookie', document.cookie);
log('HttpOnly session cookie readable?',
  document.cookie.includes('session=') ? 'yes' : 'no');

// 4. IndexedDB: asynchronous, structured objects, indexes
const db = await new Promise((resolve, reject) => {
  const open = indexedDB.open('notes-lab', 1);
  open.onupgradeneeded = () => {
    const store = open.result.createObjectStore('notes', { keyPath: 'id' });
    store.createIndex('by-tag', 'tags', { multiEntry: true });
  };
  open.onsuccess = () => resolve(open.result);
  open.onerror = () => reject(open.error);
});
const note = { id: 7, text: 'renew passport', tags: ['admin', 'urgent'] };
const stored = await new Promise((resolve, reject) => {
  const tx = db.transaction('notes', 'readwrite');
  tx.objectStore('notes').put(note);
  tx.oncomplete = () => resolve('stored');
  tx.onerror = () => reject(tx.error);
});
log('indexedDB put', stored);
const byTag = await new Promise((resolve, reject) => {
  const req = db.transaction('notes').objectStore('notes')
    .index('by-tag').getAll('urgent');
  req.onsuccess = () => resolve(req.result);
  req.onerror = () => reject(req.error);
});
log('indexedDB by tag "urgent"', JSON.stringify(byTag.map((n) => n.text)));

// 5. Cache API: Request and Response pairs, keyed by request
const cache = await caches.open('demo-v1');
const res = new Response('The answer is 42.');
await cache.put('/shared-answer', res);
const hit = await cache.match('/shared-answer');
log('cache.match', await hit.text());

// 6. quota: localStorage throws when a value does not fit
try {
  localStorage.setItem('huge', 'x'.repeat(11 * 1024 * 1024));
  log('huge write', 'accepted');
} catch (err) {
  log('huge write', err.name);
}
Expected output
localStorage raw: {"id":1,"text":"buy milk","tags":["home"]}
sessionStorage: half-written note
document.cookie: theme=dark
HttpOnly session cookie readable?: no
indexedDB put: stored
indexedDB by tag "urgent": ["renew passport"]
cache.match: The answer is 42.
huge write: QuotaExceededError

Three details in that run are worth pausing on. The raw localStorage value is one JSON string: the object was flattened on the way in, and JSON.parse is your job on the way out — that parse is also what makes heavy localStorage use a main-thread problem (see Unblocking the main thread). The IndexedDB record stayed a real object and came back through the by-tag index, which is a real query. The page set one cookie (theme=dark) and could read it back, but the HttpOnly session cookie the server sent is invisible to document.cookie — that is the attribute doing its job.

As a rule of thumb: data the server must see on every request goes in a cookie; tiny preferences live in localStorage; anything the app queries, edits or must work with offline belongs in IndexedDB; and things fetched over HTTP — pages, scripts, API GET responses — belong in the Cache API. (In production, wrap IndexedDB with a small promise helper such as idb, or use a library; the raw events API is shown here once so the wrapper is not magic.)

03. Capacity, persistence and eviction

Quota is per origin, and for IndexedDB and the Cache API it is generous: browsers typically allow a large fraction of free disk space to a single site, shared across that origin's IndexedDB databases and caches. Cookies and Web Storage are the exceptions — kilobytes and roughly 5 MB respectively. navigator.storage.estimate() reports what the browser has granted and used so far:

JavaScript · checking the quota on a fresh profile
const log = (label, value) => console.log(label + ': ' + value);
const est = await navigator.storage.estimate();
log('storage.estimate quota', est.quota);
log('storage.estimate usage', est.usage);
let persisted = null;
try {
  persisted = await navigator.storage.persist();
} catch (err) {
  persisted = 'error: ' + err.name;
}
log('storage.persist', persisted);
Illustrative output (Chromium 156, run after the snippet above; quota and usage depend on the machine)
storage.estimate quota: 10737492150
storage.estimate usage: 73910
storage.persist: false

On the machine this ran on, about 10 GB was granted against roughly 74 KB used — numbers that vary by browser and free disk space, not a spec constant. The important part is what the quota implies: IndexedDB comfortably holds a whole app's working set, so "will it fit?" is rarely the deciding factor; access pattern and lifetime are.

Stored data is best-effort by default: under disk pressure the browser may evict data from origins it considers unused, without asking. navigator.storage.persist() asks the browser to treat the origin's data as persistent and exempt from that automatic eviction. The grant is heuristic — browsers say yes more readily to installed apps and sites the user engages with, and the fresh automated profile above was refused. persisted is your answer, and it is worth checking before betting an offline workflow on data that the browser may clear.

04. Exposure to scripts and privacy

Every store in this lesson is readable by any script running on the origin — first-party code, bundled dependencies, and anything injected through a cross-site scripting hole. The one exception is an HttpOnly cookie, which the HTTP layer withholds from document.cookie entirely. That asymmetry drives a clear rule: a session identifier belongs in an HttpOnly cookie set by the server, not in localStorage where a single injected script can copy it out. Token-in-Web-Storage patterns trade a real, common attack for a little convenience.

The same exposure cuts across accounts. Shared-device users, public terminals and account switchers all expect that signing out leaves nothing of theirs behind for the next person — or for a script still running on the page. That means application code has to partition what it stores by account (key records by user id, or use a database per account) and delete the stores on sign-out. The Cache API needs the same care: a response cached by a service worker is shared by every user of that browser, which is why private API responses never belong in a shared cache — a rule the service worker lesson and the lab both apply.

Browsers also partition storage between sites. Since Chrome 115, and in Firefox and Safari, the localStorage, IndexedDB and caches of an embedded third-party frame are keyed by the top-level site as well, so the same embed on two sites sees two separate stores. Cookies differ by browser: Firefox partitions third-party cookies and Safari blocks them by default, while Chrome still sends them unless the user turns them off. All of that limits leakage between sites; it does nothing about scripts on your own origin, which is where the practical risk lives.

05. Check your understanding

Practice check · 3 questions

Choosing and using the stores

Three situations from real apps.

Q1. A page keeps a 2 MB JSON string in localStorage and parses it on every keystroke to filter a list. Typing stutters. What is the most accurate explanation?
Q2. A user has the app open in one tab and then opens the same origin in a brand-new second tab. What does the second tab see?
Q3. A script stored a Response with cache.put('/report', res) in an open cache. What does cache.match('/report?month=9') return?
Practice only: not graded, not saved, not evidence.

06. Apply it

Take the notes app from this skill's practice task — or any app you know well — and make the storage decision explicitly for each kind of data it keeps:

  1. The signed-in session: which store, and which cookie attributes does the server need?
  2. The notes themselves, including tags and a "find by tag" feature: which store, and what indexes?
  3. UI preferences such as theme: which store, and what happens if it is empty?
  4. The HTML, JavaScript and CSS needed to start the app with no network: which store?

Then write the sign-out routine: what must be cleared so the next account on this browser sees nothing of the previous one? Note which of those clearances the server must also do.

07. Review prompt

Without looking back: name the four stores and, for each, its access style (synchronous or asynchronous), roughly what it holds, and its lifetime. Which one can the server both write and read on every request, and which one is hidden from document.cookie when HttpOnly is set? Finally: what does navigator.storage.persist() change, and why might a browser refuse it?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check