What you'll learn: By the end of this lesson you will be able to say exactly which pages see a cookie (host-only or
Domain, path, and why port and scheme do not matter) and which pages see alocalStorageorsessionStorageentry (origin, and tab), explain how each one expires or is replaced and deleted, read whatdocument.cookieshows, count what a cookie adds to every request, and find the bugs that come from two cookies sharing a name.
Think of a company's mailroom. A cookie is a stamp the mailroom told you to press on every envelope you send it, and the stamp goes on every envelope to that address, even ones for the loading dock. Web Storage is a drawer in your own desk: nobody at the mailroom ever sees it, and only your own pages can open it. The two are easy to mix up because both hold a name and a value. They are scoped, kept and sent in different ways.
The running example is the made-up shop at shop.example, with an API at api.shop.example, a blog at blog.shop.example and a staging copy on port 8443. Browser Storage: Cookies, Web Storage, IndexedDB and the Cache API chooses between all the stores; this lesson goes deep on two of them. Security attributes (HttpOnly, SameSite, prefixes) are in Token Storage and Secure Cookies, and quota errors and the storage event in State Persistence and Synchronization. Here the question is: who sees it, how long does it live, and what does it cost?
The core idea
- Cookies are scoped by host and path, and are blind to port and scheme. Web Storage is scoped by origin (scheme, host and port), and
sessionStoragealso by tab. - A cookie is a request header with a storage side effect. Whatever the jar holds for a URL travels with every request to it. Web Storage never travels.
- Same name does not mean same value. A cookie is identified by name, scope and path, so two cookies can share a name, and a deletion removes only the one it names exactly.
Three illustrations run through the lesson: a minimal example (one value written to both), a realistic example (the shop's host, port and scheme variants) and a failure example (two theme cookies).
Cookies as storage
A cookie is a name and a value the server asks the browser to keep (Set-Cookie) or script writes through document.cookie, and that the browser sends back in a Cookie header. MDN says the browser "usually sends previously stored cookies for the current domain back to the server".
Reading and writing. document.cookie reads as one string of name=value pairs joined by ; . A cookie with HttpOnly is not in it, and neither are attributes. Writing sets one cookie per assignment. You cannot change a cookie by sending your own Cookie header from fetch(), MDN says, for security.
Identity. The browser treats a cookie as the same one when name, domain scope and path match. Set it again and the new value replaces the old (the lab prints replaced). A different path makes a different cookie.
Lifetime. A cookie without Max-Age or Expires is a session cookie, deleted "when the current session ends". MDN adds that the browser defines when that is and that some browsers restore sessions, which "can cause session cookies to last indefinitely". With Max-Age (or Expires) it is persistent. Max-Age takes precedence when both are set. To delete a cookie, set it again with the same name, path and domain and a Max-Age of zero or less.
Size and count. RFC 6265 asks browsers to support at least 4096 bytes per cookie, 50 per domain and 3000 in total. MDN says the per-domain maximum varies by browser and a cookie is usually limited to 4 KB.
Cost. MDN: "Cookies are sent with every request, so they can worsen performance (for example on slow mobile data connections), especially if you have a lot of cookies set."
Who sees a cookie
Two attributes decide it, plus one the browser enforces.
Domain. Without it the cookie is host-only: only the exact host receives it. WithDomain=shop.example, MDN says, it is available "on the specified server and its subdomains". A server can setDomainonly to its own host or a parent, never to a sibling or a child.Path. The cookie is sent only when the request path matches on a directory boundary:Path=/docsmatches/docs,/docs/and/docs/Web/HTTP, not/docsetsor/. MDN is blunt that this "is not intended as a security measure".Secure. The cookie is sent only over HTTPS, and anhttp:page cannot set it (localhost is an exception in some browsers).
What the list leaves out is the point: neither port nor scheme isolates a cookie. RFC 6265, section 8.5, says "Cookies do not provide isolation by port" and "Cookies do not provide isolation by scheme". Web Storage is the opposite: MDN says localStorage for http://example.com is a different object from localStorage for https://example.com.
Figure 1. A cookie follows the host, Web Storage follows the origin
How to read this: the shop is shop.example, the API host is api.shop.example, staging is shop.example:8443. The cookie jar feeds every host the cookie matches, whatever its subdomain or port. The localStorage box has no outgoing arrow: other origins cannot read it and it is never sent.
Illustration 1 (minimal) and 2 (realistic): one value, six pages
The lab writes pref=dark to localStorage and sets three cookies from https://shop.example/: a host-only one, one with Domain=shop.example, and one with Domain=shop.example plus Secure. Then it asks which of six pages sees each.
Expected output, captured from a real run (Node 26.13.1, 2026-12-01, section 1):
=== 1. One value, written from https://shop.example/. Who sees it?
page URL localStorage cookie host-only cookie Domain cookie Domain+Secure
https://shop.example/ yes yes yes yes
https://shop.example:8443/ no yes yes yes
http://shop.example/ no yes yes no
https://api.shop.example/ no no yes yes
https://shop.example.test/ no no no no
https://other.example/ no no no no
Row by row: the staging copy on port 8443 sees all three cookies and no localStorage. The plain http: page sees the two cookies without Secure. The API host sees only the Domain cookies. A page on shop.example.test sees nothing, because a Domain match needs a dot boundary. (The lab skips SameSite and the Public Suffix List.)
Who sees a Web Storage entry
MDN describes both areas by two words. localStorage is "partitioned by origin only": all documents of one origin, in every tab, share it, and it persists when the browser closes. sessionStorage is "partitioned by browser tabs and by origin": each origin in a tab has its own area, and closing the tab destroys the data. Both keep strings only, and both are synchronous.
The page session has three details worth knowing:
- A reload keeps it. MDN: a page session "survives over page reloads and restores".
- A new tab starts empty. MDN says opening a page in a new tab or window "creates a new session", which differs from how session cookies work. The exception is a page with an
opener: itssessionStoragestarts as a copy of the opener's, and the two are separate afterwards. - Another origin has its own area. Navigating the tab to a different origin and back finds the first origin's data waiting.
Figure 2. Which area a page gets
Web Storage"] --> O{"Origin is a valid
scheme, host, port?"} O -->|"no, for example data:"| E["SecurityError"] O -->|"yes"| W{"Which area?"} W -->|"localStorage"| L["One area per origin,
shared by all tabs"] W -->|"sessionStorage"| S["One area per tab and origin,
gone when the tab closes"]
How to read this: the first question is whether the page has an origin at all. After that, localStorage depends on the origin only and sessionStorage on the origin and the tab.
MDN also says a browser may give a private-browsing page an empty localStorage with a quota of zero, and users can disable storage without hiding the global object, so be ready for a SecurityError on access and a QuotaExceededError on write.
Expected output, captured from a real run (Node 26.13.1, 2026-12-01, section 2):
=== 2. Two tabs on one origin: localStorage is shared, sessionStorage is per tab
tab B reads localStorage theme: dark
tab B reads sessionStorage step: null
tab A after a reload, step: payment
tab A on other.example, step: null (another origin has its own area)
tab A back on shop.example, step: payment
tab opened from A, starts with a copy: payment
after the child changes it: child=done A=payment (separate afterwards)
closing A: session areas 2 -> 1; local origins 1 -> 1
a new tab: theme=dark, step=null
What a cookie costs
Web Storage costs nothing on the wire. A cookie adds a Cookie header line to every matching request. The lab counts it: a session cookie of 17 characters, then the same page with a 60-character cart added as a second cookie, on a page that makes 30 same-site requests (the 30 is illustrative).
Expected output, captured from a real run (Node 26.13.1, 2026-12-01, section 4):
=== 4. What a cookie costs: it rides on every request
cart as JSON text: 60 characters
one request, session cookie only: 31 bytes of Cookie header
one request, cart also in a cookie: 98 bytes of Cookie header
a page that makes 30 same-site requests (illustrative):
session cookie only: 930 bytes sent
cart also in a cookie: 2940 bytes sent
cart in localStorage: same as the first line (Web Storage is never sent)
a 4100-character cookie value: {"ok":false,"reason":"too-large"}
The bytes scale with the cart and are sent on requests for images and scripts too. The lab refuses a 4100-character value because it exceeds its 4096 limit; real browsers differ.
Illustration 3 (failure): two cookies named theme
Cookies are identified by name, domain scope and path, so the same name can exist twice. The common route is a migration: theme was a host-only cookie on shop.example, and a new release sets theme with Domain=shop.example so the blog can read it too. The old cookie is still there.
Expected output, captured from a real run (Node 26.13.1, 2026-12-01, section 7):
=== 7. Two cookies with one name: a host-only cookie left behind, a Domain cookie added
cookies stored: 2
at shop.example: Cookie: theme=light; theme=dark
at blog.shop.example: Cookie: theme=dark
after deleting the host-only one: Cookie: theme=dark
The shop receives both. RFC 6265 says a browser SHOULD list cookies with longer paths first and, among equal paths, earlier-created ones first (not all browsers do), so the stale light can come first, and server code that reads "the" theme cookie may well take it. The same RFC says servers should not rely on the order. The blog sees only the new one, so the two sites disagree. Deleting works only when you name the exact cookie: the lab's delete with no Domain removed the host-only one and left the shared one.
Figure 3. Two cookies, one name
How to read this: the browser compares name, domain scope and path, so the second Set-Cookie did not replace the first. The old cookie keeps being sent until something deletes it by its own scope.
Choosing between them
| Question | Cookie | Web Storage |
|---|---|---|
| Does the server receive it? | Yes, on every matching request | No |
| Visible to a subdomain? | With Domain, yes |
No: a different origin |
| Visible to another port or scheme? | Yes, unless Secure blocks it |
No |
| Shared between tabs? | Yes | localStorage yes, sessionStorage no |
| Value type | String, about 4 KB | String; calls are synchronous |
| Expires on its own? | With Max-Age or Expires |
localStorage never, sessionStorage with the tab |
Build it: scope, lifetime and cost, runnable
Goal. Run a model of Web Storage (tabs, origins, opener copy) and a cookie jar (host-only versus Domain, path, lifetime, header bytes) through the situations above.
Setup. The lab is in the course's example workspace (Node 26.13.1). It is a model, not a browser.
cd examples/frontend
pnpm install
cd labs/web-storage-vs-cookies
pnpm test # 29 tests
node src/demo.ts
Steps.
- Run the tests and the demo.
- In section 1, find the one cell where cookies and storage disagree most: the
:8443row, where the cookie arrives and the storage does not. - In section 7, find the line that proves a delete removes one cookie, not every cookie with that name.
What the lab does not show. It runs no browser. It leaves out SameSite, prefixes, the Public Suffix List, third-party blocking, cookie counts and eviction, the storage event, quotas and private browsing. The 30 requests and the cart are made up, and the 4096 limit is the lab's choice.
Break it. In src/cookies.ts, delete the line .filter((c) => !c.secure || u.protocol === "https:"). A Secure cookie would then be sent over http:, and the test "keeps a Secure cookie off http" fails. Revert it.
In practice: a theme that resets on the blog
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
The shop keeps the dark-mode choice in localStorage. The blog is on a subdomain. Readers who chose dark on the shop see a white blog and file bug reports.
Starting architecture
Figure 4. Starting point: one preference, two origins
How to read this: the shop is shop.example and the blog is blog.shop.example. The red arrow is the finding: a subdomain is a different origin, so the blog's localStorage is a different object.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
A Domain=shop.example cookie |
Both sites read it, the server can render the theme | Bytes on every request, and every subdomain sees it | Old same-name cookies linger |
localStorage on each site plus a server preference |
No bytes on requests | Two copies to keep in step, needs sign-in | Anonymous readers still reset |
| A shared script that copies through a page-to-page message | No cookie | A cross-origin messaging contract | Complex for a four-letter value |
The decision
| Field | Decision record |
|---|---|
| Context | One tiny preference must reach every subdomain, and the server wants it for the first paint. |
| Decision | Set theme as a Domain=shop.example cookie with a one-year Max-Age. Delete the old host-only cookie in the same release. Security attributes follow the token lesson. |
| Consequences, good | One value on every site, no flash of the wrong theme. |
| Consequences, bad | A few bytes on every request to every subdomain, and any subdomain can read and set it. |
| Revisit when | The preference becomes per-user data that follows a signed-in account: then it moves to the server. |
Rollout and verification
- Delete the old cookie first with a
Max-Ageof zero and the same name, path and host-only scope, then set the new one. - Read cookies by name and scope in server code and decide what to do if two arrive.
- Check the
Cookieheader on a request from each subdomain.
The 2 a.m. failure
After release, some readers still see light on the shop and dark on the blog (illustrative). The shop receives theme=light; theme=dark, because the old cookie was never deleted: the cleanup that shipped carried Domain=shop.example, so it matched the new cookie's scope and left the host-only original alone.
First three checks: (1) print the raw Cookie header and count the theme entries; (2) list the cookies in the browser's storage panel by domain and path; (3) check which one the server reads. Mitigation: expire both scopes explicitly, and read the newest value deliberately. Follow-up: add a test that sends two same-name cookies to the parser, and log how many requests carry duplicates.
Architect's notes
- Describe a cookie by name, scope and path, never by name alone.
- For isolation use different hosts, not different ports: a cookie ignores the port.
- Every
Domaincookie is shared with every subdomain. Decide who may set it.
The other side of this topic
On the server, the same question is how a service knows who is calling when the browser only sends a header: the back-end lessons on stateless services and on replication lag and read-your-writes cover what a request needs to carry and why a read can be stale.
Common mistakes
- Assuming a different port is isolated. The cookie arrives anyway.
- Assuming a subdomain shares
localStorage. It does not. - Deleting a cookie without its scope, so it remains.
- Treating
sessionStoragelike a session cookie. It is per tab and starts empty in a new tab, apart from the opener copy.
Key takeaways
- A cookie is identified by name, domain scope and path; a host-only cookie is not the same as a
Domaincookie. - Cookies ignore port and scheme (except
Secureneeding HTTPS); Web Storage is keyed by origin. localStorageis shared by all tabs;sessionStorageis per tab and origin, survives reloads and starts as a copy only for an opened-from page.- Delete a cookie by setting it with the same scope and
Max-Ageof zero or less. - A cookie costs bytes on every matching request; Web Storage costs none.
Practice exercises
Exercise 1 — Starter (45 min): In the lab, add a cookie with Path=/api and write down, for six URLs, which requests carry it. Compare with the test list.
Exercise 2 — Intermediate (2 hours): Add a storage event to the browser model that reaches the other tabs of the origin only, and test that sessionStorage tabs get none.
Exercise 3 — Advanced (half day): Make the jar refuse a cookie when a host already has a set number of cookies, decide which cookie to evict, and justify the rule.
Related reading
In this course:
- Browser Storage: Cookies, Web Storage, IndexedDB and the Cache API, the comparison this lesson deepens.
- Token Storage and Secure Cookies, cookie attributes as security controls.
- State Persistence and Synchronization, the
storageevent and quota errors.
Official documentation
- MDN: Using HTTP cookies,
Domain,Path, lifetime and limits. - RFC 6265: HTTP State Management Mechanism, sections 6.1 and 8.5.
- MDN: Window.sessionStorage and Window.localStorage.
- MDN: Web Storage API and Using the Web Storage API.
- HTML Standard: Web storage.