Skip to content

    Frontend System Design

    Token Storage and Secure Cookies

    Decide where a sign-in credential should live in a browser app, memory, Web Storage or a cookie, and set Secure, HttpOnly, SameSite and __Host- correctly.

    By Published 20 min read

    • frontend-system-design
    • security
    • cookies
    • authentication
    Share

    Flagship lessonintermediateTypeScript labFrontend System Design

    Before this: OAuth 2.0, OIDC and PKCE in Single-Page Apps, Cookies and Web Storage in Depth

    What you'll learn: By the end of this lesson you will be able to say what a bearer credential is, compare four places a browser app can keep one (a JavaScript variable, sessionStorage, localStorage, a cookie) against the same attacks, set each cookie attribute (Secure, HttpOnly, SameSite, Domain, Path, Max-Age, the __Host- and __Secure- prefixes) and predict what the browser accepts and sends, explain why HttpOnly stops theft but not use, and choose a storage pattern for a single-page app. A small TypeScript model of a browser's cookie rules lets you check every prediction.

    Think of the key card for your hotel room. You can carry it in your pocket, where only you can use it. You can leave it on the lobby desk, where anyone can pick it up. Or you can arrange for the door to recognise you and open by itself, which is convenient until someone steers you to the wrong door and it opens anyway. Each choice answers two questions differently: who can pick the key up, and when does it get used without you deciding.

    A browser app faces the same two questions about its sign-in credential. Who can read it? Your own code, a third-party script, a script an attacker injected. When is it sent? Only when your code attaches it, or automatically on every request to a site. This lesson answers both on purpose.

    The running example is the account area of a shop at https://shop.example: a single-page app that shows orders and addresses, calling an API at https://api.shop.example. (The .example names are reserved for documentation, and no value in this lesson is a real token.) If origins and sites are not yet clear to you, read The Same-Origin Policy and CORS first; this lesson relies on it.

    The core idea

    Hold on to three statements.

    1. A credential in the browser has two exposures: reading and sending. Reading is about which scripts can get the value. Sending is about which requests carry it without your code's help. Each storage place trades one against the other.
    2. No place is safe from script you do not control, but places differ in what the attacker walks away with. An attacker script in your page runs with the page's privileges. An HttpOnly cookie stops that script from copying the value and using it somewhere else later. It does not stop it from calling your API while the page is open.
    3. Cookies move the problem from "read" to "send", and attributes are how you manage it. Secure, HttpOnly, SameSite, Domain and the prefixes decide who can read the cookie and which requests carry it. Set them all explicitly.

    This lesson cites the IETF's cookie specification (RFC 6265bis, a draft at the time of writing), MDN and OWASP's cheat sheets. XSS defences, CSRF defences, OAuth with PKCE and JWTs have their own lessons; here they appear only as far as storage needs them.

    What we are protecting

    Most browser apps end up holding a session identifier (an opaque random string the server looks up), an access token (a credential for an API, sometimes a signed JWT) or a refresh token (used to get new access tokens). All three are bearer credentials: RFC 6750 defines a bearer token as one that any party in possession of it can use in the same way as any other party. Nothing proves the sender is the party it was issued to.

    So possession is the attack: anything that copies the value, whether script, a proxy log or someone who can see the device, can use it from elsewhere until it expires or the server revokes it. And where it travels matters. RFC 6750 says clients must use TLS for every request that carries a bearer token, that token servers should issue short-lived tokens (one hour or less, naming browser-based clients as a reason), and that tokens should not go in a URL query parameter, because URLs end up in logs. OWASP's Session Management Cheat Sheet adds backend rules a front-end designer should know exist: at least 64 bits of entropy in a session identifier, a new identifier after a privilege change such as signing in, and an absolute session timeout. The browser's half is where the value sits and how it travels.

    Four places to keep a credential

    Figure 1. Where a credential can live, and who can reach it

    Four places in the browser to keep a credential, and what can reach eachYour app code to JavaScript variable (read, write); Your app code to Web Storage (getItem, setItem); Injected script to Web Storage (reads it too); Cookie jar to API (attached automatically); Your app code to API (adds a header)PAGE ON SHOP.EXAMPLEBROWSER STORAGEYour app code: same originYour app codesame originInjected script: XSSInjectedscriptXSSJavaScript variable: gone on reloadJavaScriptvariablegone on reloadWeb Storage: local and sessionWeb Storagelocal and sessionCookie jar: browser managedCookie jarbrowser managedAPI: api.shop.exampleAPIapi.shop.exampleread, writegetItem, setItemreads it tooattached automaticallyadds a header

    How to read this: your code and an injected script share the page, so anything the page can read through an API, the injected script can read too. The cookie jar is different: the browser, not the page, attaches its contents to requests.

    A JavaScript variable

    The credential lives in a module or closure and is never written anywhere. A reload loses it, and so does opening a second tab, so the app must get a new one (usually with a cookie, see below). No storage API exposes the value, so an attacker script cannot simply call getItem. That is a real but modest gain: RFC 10017 (OAuth 2.0 for Browser-Based Applications, August 2026) warns that malicious JavaScript "has the same privileges as the legitimate application code", so it can still call your authenticated functions or start a fresh sign-in. Treat memory as the least exposed place to keep a token in script, not as a safe one.

    sessionStorage and localStorage

    MDN describes both as per-origin string stores. sessionStorage is available for the page session (it survives reloads and restores) and is shared only inside one tab. localStorage persists when the browser is closed and reopened and is shared by all tabs of the origin. Pages on other origins cannot reach either one. State Persistence and Synchronization covers how they work in detail.

    What matters here is that any script running on the origin can call them. OWASP's HTML5 Security Cheat Sheet says not to store session identifiers in local storage "as the data is always accessible by JavaScript", and that a single XSS flaw can steal everything in those objects. OWASP's Session Management Cheat Sheet, at the time of writing, goes further: no authentication tokens, session IDs, JWTs, refresh tokens or any credential in either store.

    A cookie is a small value the browser stores for a site and sends back automatically with later requests to it. MDN says the browser "usually sends previously stored cookies for the current domain back to the server within a Cookie HTTP header". Because the browser does the sending, an HttpOnly cookie can be used without script ever seeing it. That is the appeal and the risk: the browser also sends it when another site triggers the request.

    A server creates a cookie with a Set-Cookie response header. The browser stores it, and each later matching request carries Cookie: name=value.

    Figure 2. A cookie's round trip

    sequenceDiagram accTitle: Setting a cookie and having it returned accDescr: The browser posts a sign-in form. The server responds with a Set-Cookie header. The browser stores the cookie. Later, the page calls the API and the browser attaches a Cookie header without the page's code adding it. Script reading document.cookie does not see an HttpOnly cookie. participant B as Browser participant S as Server B->>S: POST /login (credentials) S-->>B: 200 with a Set-Cookie header (name, Path, Secure, HttpOnly, SameSite) Note over B: stores the cookie under its name, domain and path B->>S: GET /api/orders (page code adds no credential) Note over B: attaches Cookie: __Host-sid=... S-->>B: 200 orders Note over B: document.cookie does not list an HttpOnly cookie

    How to read this: the page's code never touches the cookie. The browser stores it from the response and attaches it later. That is why it can be hidden from script and why it can also be sent when you did not mean it to be.

    Illustration 1 (minimal example): one header, read attribute by attribute

    The lab builds __Host-sid=demo-session-0001; Path=/; Secure; HttpOnly; SameSite=Lax for the shop's sign-in (the value is made up). The prefix is a promise the browser enforces, Path=/ says which paths carry it, Secure limits it to https:, HttpOnly hides it from script (though MDN notes it "will still be sent with JavaScript-initiated requests"), and SameSite=Lax limits cross-site sending. No Domain is present, deliberately.

    Secure and HttpOnly

    MDN says a Secure cookie is sent only when a request is made with the https: scheme (except on localhost), and that insecure http: sites cannot set Secure cookies. It is not a guarantee on the device: MDN notes such a cookie can still be read from the client's disk, or from JavaScript if HttpOnly is not set. And the specification says Secure does not provide integrity in the presence of an active network attacker, so treat it as one control among several.

    HttpOnly stops script reading the cookie through document.cookie. MDN lists it as a mitigation against XSS. It does not stop the browser attaching the cookie to requests, including ones made by injected script.

    SameSite and what "site" means

    A site is a scheme plus a registrable domain, so https://shop.example and https://api.shop.example are the same site and different origins (the previous lesson gave the precise difference). MDN defines a cross-site request as one where the site and/or the scheme does not match the site the user is visiting. SameSite says which requests carry the cookie:

    Value Sent on same-site requests Sent on cross-site requests
    Strict yes no
    Lax yes only top-level navigations that use a safe method such as GET (a link click), not subresource loads or POST
    None yes yes, and Secure is required

    Two details matter in practice. MDN says "some browsers" use Lax as the default when the attribute is missing, which means the default is not something to lean on: always write the attribute. And MDN adds that where Lax is applied as a default, a more permissive version is used, which also allows the cookie on POST requests for a short time (no more than two minutes) after the cookie was set. The RFC says an unrecognised SameSite value is treated as Lax, and that None without Secure is ignored.

    Domain and Path

    If you omit Domain, the cookie is a host-only cookie, returned only to the host that set it. With Domain=shop.example, MDN says the cookie becomes available to that domain and all its subdomains. OWASP warns that this lets an attacker who controls any sibling subdomain target your sessions, and advises leaving Domain unset.

    Path limits which request paths carry the cookie, but MDN is explicit that it "is not intended as a security measure, and does not protect against unauthorized reading of the cookie from a different path". Nor does anything isolate ports: the RFC points out that cookies for a host are shared across all ports on that host.

    Prefixes: __Secure- and __Host-

    A cookie name that starts with a prefix tells the browser to refuse the cookie unless its attributes match. MDN gives the rules:

    • __Secure- cookies must be set with Secure by a secure page.
    • __Host- cookies must be set with Secure by a secure page, must not have a Domain, and must have Path=/.
    • __Http- and __Host-Http- additionally require HttpOnly.

    The RFC says browsers must match prefixes case-insensitively. A __Host- cookie must be host-only, so it cannot be widened to subdomains with a Domain attribute. MDN warns that on browsers that do not support prefixes, "prefixed cookies will always be accepted", so the prefix is an extra assurance, not the only control. OWASP recommends __Host- for session identifiers.

    Lifetime: session or persistent

    Without Expires or Max-Age, a cookie is a session cookie, though MDN warns that session restore may bring it back "as if the browser was never closed". Max-Age is a lifetime in seconds: zero or negative expires the cookie at once, and when both attributes are set, Max-Age wins. The specification says a user agent should not keep a cookie more than 400 days ahead, and that a cookie whose name and value together exceed 4096 octets is ignored, so a cookie is the wrong place for a large token. OWASP advises non-persistent cookies when authentication need not survive the browser session, and notes that deleting a cookie does not invalidate a stolen copy of the session ID.

    Will the browser send it?

    Put the rules together and a cookie is attached to a request only if every test passes.

    Figure 3. The questions a browser asks before attaching a cookie

    flowchart TD accTitle: Will a stored cookie be attached to this request accDescr: A decision flow. The cookie must be unexpired, its host must match (exactly for a host-only cookie, or the domain and subdomains for a Domain cookie), its path must match, a Secure cookie needs an https request, and SameSite must allow it: Strict needs a same-site request, Lax also allows a cross-site top-level navigation with a safe method, None allows all. A{"Unexpired?"} -->|"no"| X["Not sent"] A -->|"yes"| B{"Host matches?
    (host-only: exact,
    Domain: that domain
    and subdomains)"} B -->|"no"| X B -->|"yes"| C{"Path matches?"} C -->|"no"| X C -->|"yes"| D{"Secure cookie and
    request not https?"} D -->|"yes"| X D -->|"no"| E{"Cross-site request?"} E -->|"no"| S["Sent"] E -->|"yes"| F{"SameSite value"} F -->|"None"| S F -->|"Lax"| G{"Top-level navigation
    with a safe method?"} G -->|"yes"| S G -->|"no"| X F -->|"Strict"| X

    How to read this: the lab implements this flow, and its demo prints the reason each cookie was or was not sent. Notice that SameSite is only the last gate: a cookie can fail on host, path or scheme long before.

    Cookies and the attack that rides them

    Because the browser attaches cookies by itself, another site can cause your user's browser to send a request to yours, and the cookie goes along. This is cross-site request forgery (CSRF). SameSite is the browser-side brake: with Strict or Lax, a cross-site POST does not carry the cookie. OWASP treats it as defence in depth, not a replacement for CSRF tokens, and RFC 10017 says a backend with a cookie session must implement a proper CSRF defence, and that SameSite=Strict alone is not enough when the backend shares a site with other applications (a subdomain takeover can enable CSRF). The CSRF lesson in this course goes deeper. For storage, the point is that choosing a cookie means accepting a CSRF obligation, which tokens kept in script do not carry, because the browser never sends those by itself.

    Illustration 2 (realistic example): the shop after sign-in

    The lab signs a shopper into https://shop.example (a __Host- session cookie that is HttpOnly and Lax, plus theme, a locale cookie with Domain=shop.example, and a cartid cookie on Path=/cart) and makes seven requests. Three rows in the output are worth a pause:

    • A call to api.shop.example carries only locale. Same site, but the session cookie is host-only. An app and an API on different hosts need a design (a backend on the page's origin, or a token), not a widened Domain.
    • A POST from evil.example carries nothing: SameSite=Lax doing its job.
    • A link click from evil.example carries the session cookie, because Lax allows a top-level GET navigation. A GET that changes state is a CSRF hole.

    What HttpOnly stops, and what it does not

    Figure 4. The same XSS flaw against two storage choices

    sequenceDiagram accTitle: An injected script against a localStorage token and an HttpOnly cookie accDescr: An attacker script runs in the page. If the token is in localStorage, the script reads it and sends it to the attacker, who can use it later from anywhere. If the credential is an HttpOnly cookie, the script cannot read it, so it can only make requests from the open page, which the browser decorates with the cookie. participant A as Attacker script in the page participant L as localStorage token participant C as HttpOnly cookie participant S as API A->>L: getItem L-->>A: token value A->>A: send the value to the attacker's server Note over A,S: the attacker can now call the API from anywhere until the token expires or is revoked A->>C: read document.cookie C-->>A: nothing (HttpOnly) A->>S: fetch /api/orders (same origin) Note over A,S: the browser adds the cookie, but only while the page is open

    How to read this: the top path ends with a copy of the credential. The bottom path ends with a request made through the user's own page. Both are bad. The second is smaller and stops when the page closes, and it is easier to detect on the server.

    In the lab's section 3, document.cookie lists theme, locale and cartid but not the session cookie, yet the first request of that section carries it. In section 6, the line "injected script acts as the user" is yes for every place. That is the honest answer: whichever store you pick, injected script can use the signed-in session while the page is open. The defence is to keep the script out (output encoding, a Content Security Policy, vetted dependencies) and to limit what a stolen session can do, which the XSS and CSP lessons cover.

    Choosing a pattern

    Real systems combine the places above into a few patterns. RFC 10017 names three architectures for browser-based OAuth applications, which gives a vocabulary:

    • Backend for frontend (BFF). A server on the same site (ideally the same origin) is the OAuth client and holds the tokens. The browser holds only a session cookie. The RFC says that since tokens are only available to the BFF, there are none to extract from the browser. The BFF must set Secure and HttpOnly, should use SameSite=Strict, should not set Domain, and should use a prefix such as __Host-Http-. The Backend for Frontend from the Client's Side covers the client side.
    • Token-mediating backend. A backend obtains tokens, but the browser receives the access token and calls APIs directly. Refresh tokens stay out of the browser. The access token lives in memory, so your code must handle its short lifetime.
    • Browser-based OAuth client. The page itself runs the OAuth flow and holds the tokens as a public client. The RFC warns this pattern is vulnerable to all the attack scenarios it describes, and lists mitigations such as keeping the refresh token isolated in a Web Worker, or sender-constraining tokens (DPoP). Use it only when you cannot run a backend.

    Figure 5. Where should the credential live?

    flowchart TD accTitle: Choosing where a browser app keeps its credential accDescr: If a same-site backend can hold the credentials, use a Secure HttpOnly host-only cookie session, with CSRF defences. If not, and the API must be called from the browser, keep a short-lived access token in memory and keep the refresh token out of script storage if you can. Never put a credential in localStorage or a URL. Q1{"Can a backend on the
    same site hold the
    credentials?"} -->|"yes"| B["Session cookie:
    __Host-, Secure, HttpOnly,
    SameSite, + CSRF defence"] Q1 -->|"no"| Q2{"Must the browser call
    APIs on other origins?"} Q2 -->|"yes"| M["Short-lived access token
    in memory, refresh kept
    out of script storage"] Q2 -->|"no"| B M --> N["Plan for reload:
    get a new token silently"] B --> P["Plan for logout:
    end the session on the server"] L["localStorage, URL,
    cookie without attributes"] -.-> R["Avoid"]

    How to read this: the left branch is the default recommendation when you control a backend. The right branch is a fallback with a heavier client burden. The dashed box is what to leave out.

    Pattern Reading exposure Sending exposure Survives reload Main cost
    Session cookie (__Host-, Secure, HttpOnly, SameSite) Not readable by script Browser attaches it, so CSRF must be handled Yes Needs a same-site backend, CSRF defence, session store
    Access token in memory, refresh through a backend Reachable only through code that holds the variable Your code attaches it No, needs a silent refresh Refresh flow, token lifetime handling
    Token in localStorage Any script on the origin can read it Your code attaches it Yes One XSS flaw copies it
    Cookie with no attributes Script can read it; sent over http: Depends on a browser default Yes The weakest of all

    Logging out

    Logging out is a server action. OWASP says that when a session ends, the application "must invalidate the session at least on server side", because clearing the cookie in the browser does not stop a copy that someone else holds. Deleting the cookie is still useful for hygiene: send the same name, domain and path with Max-Age=0. MDN also documents the Clear-Site-Data response header, which tells the browser to remove cached data, cookies and DOM storage for the site and is recommended on a logout page, so a shared computer does not keep stale local copies. Full flows are in the lesson on authentication flows from the SPA to the API.

    Goal. Predict, then check, what a browser does with a Set-Cookie header and where a credential is exposed, using a small model of the rules in this lesson. No real browser is involved.

    Setup. The lab is in the course's example workspace. It is pure TypeScript with no DOM (Node 26.13.1, pnpm).

    cd examples/frontend
    pnpm install
    cd labs/cookie-policy
    pnpm test          # 75 tests
    node src/demo.ts   # prints the six sections below

    Steps.

    1. In section 2, cover the reason and predict whether the browser keeps each header, especially __Host-sid=1; Secure (no Path=/) and sid=1; SameSite=None (no Secure).
    2. In section 3, predict the Cookie header of a request before reading it. Why does the call to api.shop.example miss the session cookie but carry locale?
    3. In section 4, predict which cookies survive at 61 and 91 seconds, including the one with both Max-Age=60 and a past Expires.
    4. In section 5, see why the second cookie reaches only "review": it has Secure and HttpOnly, but also Domain, SameSite=None and a 30-day lifetime.

    Expected output, captured from a real run (Node 26.13.1, 2026-12-01; a fixed clock and made-up cookie values):

    Token storage and secure cookies: what the browser accepts, sends and shows to script
    
    === 1. Building Set-Cookie values
    __Host-sid=demo-session-0001; Path=/; Secure; HttpOnly; SameSite=Lax
    theme=dark; Path=/; Max-Age=31536000; Secure; SameSite=Lax
    locale=en; Domain=shop.example; Expires=Fri, 01 Jan 2027 00:00:00 GMT; Max-Age=600
    refused (bad-name): "bad;name" = "x"
    refused (bad-value): "sid" = "x\r\nSet-Cookie: admin=1"
    
    === 2. Which Set-Cookie headers does the browser keep?
    stored   __Host-sid=1; Secure; Path=/
             from https://shop.example/login -> session cookie
    rejected __Host-sid=1; Secure
             from https://shop.example/login -> prefix-host-needs-path-root
    rejected __Host-sid=1; Secure; Path=/; Domain=shop.example
             from https://shop.example/login -> prefix-host-forbids-domain
    rejected __Secure-id=1
             from https://shop.example/login -> prefix-secure-needs-secure
    stored   __Secure-ID=1; Secure; Domain=shop.example
             from https://shop.example/login -> session cookie
    rejected sid=1; Secure
             from http://shop.example/login -> secure-needs-https
    stored   sid=1; Secure
             from http://localhost:3000/login -> session cookie
    rejected sid=1; SameSite=None
             from https://shop.example/login -> samesite-none-needs-secure
    stored   sid=1; SameSite=None; Secure
             from https://shop.example/login -> session cookie
    rejected sid=1; Domain=partner.example
             from https://shop.example/login -> domain-mismatch
    rejected sid=1; Domain=example
             from https://shop.example/login -> domain-is-public-suffix
    stored   sid=1; Domain=.shop.example
             from https://api.shop.example/login -> session cookie
    rejected =1
             from https://shop.example/login -> empty-name
    rejected big=xxxx... (4100 characters of x)
             from https://shop.example/login -> too-large
    
    === 3. A signed-in shopper: which cookies go with which request?
    stored (session cookie): __Host-sid=demo-session-0001; Path=/; Secure; HttpOnly; SameSite=Lax
    stored (persistent cookie): theme=dark; Path=/; Secure; SameSite=Lax; Max-Age=31536000
    stored (session cookie): locale=en; Domain=shop.example; Path=/; Secure; SameSite=Lax
    stored (session cookie): cartid=9; Path=/cart; Secure; SameSite=Lax
    
    same-site POST from the shop page
      Cookie: __Host-sid=demo-session-0001; theme=dark; locale=en
      withheld cartid: path does not match
    
    shop page calls api.shop.example (same site, other host)
      Cookie: locale=en
      withheld __Host-sid: host-only cookie, different host
      withheld theme: host-only cookie, different host
      withheld cartid: host-only cookie, different host
    
    cross-site POST from evil.example
      Cookie: (none)
      withheld __Host-sid: SameSite=Lax, cross-site and not a top-level navigation with a safe method
      withheld theme: SameSite=Lax, cross-site and not a top-level navigation with a safe method
      withheld locale: SameSite=Lax, cross-site and not a top-level navigation with a safe method
      withheld cartid: path does not match
    
    cross-site link click (GET navigation) from evil.example
      Cookie: __Host-sid=demo-session-0001; theme=dark; locale=en
      withheld cartid: path does not match
    
    cross-site image load (GET subresource) from evil.example
      Cookie: (none)
      withheld __Host-sid: SameSite=Lax, cross-site and not a top-level navigation with a safe method
      withheld theme: SameSite=Lax, cross-site and not a top-level navigation with a safe method
      withheld locale: SameSite=Lax, cross-site and not a top-level navigation with a safe method
      withheld cartid: path does not match
    
    address typed with http://
      Cookie: (none)
      withheld __Host-sid: secure cookie, request is not https
      withheld theme: secure cookie, request is not https
      withheld locale: secure cookie, request is not https
      withheld cartid: path does not match
    
    same-site GET under /cart
      Cookie: __Host-sid=demo-session-0001; theme=dark; locale=en; cartid=9
    
    what script on https://shop.example/cart can read (document.cookie):
      theme=dark; locale=en; cartid=9
    the HttpOnly session cookie is missing from that list, yet the first request above still carried it.
    
    === 4. Lifetime: Max-Age, Expires and deleting
    stored (session cookie): s=1; Path=/
    stored (persistent cookie): m=1; Path=/; Max-Age=60
    stored (persistent cookie): e=1; Path=/; Expires=Tue, 01 Dec 2026 12:01:30 GMT
    stored (persistent cookie): both=1; Path=/; Max-Age=60; Expires=Tue, 01 Dec 2026 11:00:00 GMT
    t=+ 0s cookies kept: s, m, e, both
    t=+61s cookies kept: s, e
    t=+91s cookies kept: s
    delete m with Max-Age=0: deleted; cookies now: s, e, both
    delete s with another Path: ignored; cookies now: s, e, both
    unusable attributes are ignored, an unknown SameSite value reads as Lax: {"name":"A","value":"1","sameSite":"Lax"}
    
    === 5. Reviewing a session cookie against the OWASP checklist
    FAIL   sid=v1
           fail Secure: can be sent over an unencrypted request
           fail HttpOnly: any script on the page can read it
           warn SameSite: not set: browsers differ on the default, so say it explicitly
           warn prefix: no __Host- prefix, so nothing stops a later Set-Cookie from weakening the scope
    REVIEW sid=v1; Domain=shop.example; Max-Age=2592000; Secure; HttpOnly; SameSite=None
           warn SameSite: None: sent on cross-site requests, so CSRF defences must carry the load
           warn Domain: shared with every subdomain of the domain
           warn prefix: no __Host- prefix, so nothing stops a later Set-Cookie from weakening the scope
           warn lifetime: persistent: use one only if sign-in must survive closing the browser
    PASS   __Host-sid=v1; Path=/; Secure; HttpOnly; SameSite=Strict
    
    === 6. Where can a credential live? (computed from the jar and the storage definitions)
    
    JavaScript variable (memory)
      injected script reads the value:      no 
      injected script acts as the user:     yes
      cross-site POST carries it:           no 
      cross-site link click carries it:     no 
      survives a reload / a browser restart: no  / no 
      shared between tabs:                  no 
    
    sessionStorage
      injected script reads the value:      yes
      injected script acts as the user:     yes
      cross-site POST carries it:           no 
      cross-site link click carries it:     no 
      survives a reload / a browser restart: yes / no 
      shared between tabs:                  no 
    
    localStorage
      injected script reads the value:      yes
      injected script acts as the user:     yes
      cross-site POST carries it:           no 
      cross-site link click carries it:     no 
      survives a reload / a browser restart: yes / yes
      shared between tabs:                  yes
    
    cookie, no attributes (SameSite left to the browser, Lax assumed)
      injected script reads the value:      yes
      injected script acts as the user:     yes
      cross-site POST carries it:           no 
      cross-site link click carries it:     yes
      survives a reload / a browser restart: yes / no 
      shared between tabs:                  yes
    
    cookie: Secure; SameSite=None
      injected script reads the value:      yes
      injected script acts as the user:     yes
      cross-site POST carries it:           yes
      cross-site link click carries it:     yes
      survives a reload / a browser restart: yes / no 
      shared between tabs:                  yes
    
    cookie: Secure; HttpOnly; SameSite=Lax
      injected script reads the value:      no 
      injected script acts as the user:     yes
      cross-site POST carries it:           no 
      cross-site link click carries it:     yes
      survives a reload / a browser restart: yes / no 
      shared between tabs:                  yes
    
    cookie: __Host-, Secure; HttpOnly; SameSite=Strict; Path=/
      injected script reads the value:      no 
      injected script acts as the user:     yes
      cross-site POST carries it:           no 
      cross-site link click carries it:     no 
      survives a reload / a browser restart: yes / no 
      shared between tabs:                  yes

    What the lab does not show. No browser ran any of this. The model follows RFC 6265bis and MDN as read for this lesson. Real browsers differ on the default for a missing SameSite, block or partition third-party cookies, and may restore session cookies. The lab takes a tiny Public Suffix List from the caller. "Survives a browser restart" means "has a Max-Age or Expires". The memory row follows from definitions, not an experiment.

    Break it. In src/jar.ts, in attach, change request.navigation && SAFE_NAVIGATION_METHODS.includes(...) to SAFE_NAVIGATION_METHODS.includes(...). A Lax cookie would then travel on a cross-site image load, and the Lax test in test/jar.test.ts fails. Revert it, and run the tests again.

    Stretch. Pick one:

    • Add the "Lax-allowing-unsafe" rule MDN describes (a cookie with no SameSite is also sent on a cross-site POST for a short time after it was set) with an injected clock, and find a request where it changes the answer.
    • Add Partitioned cookies (they need Secure) and a second top-level site, and show the same cookie stored twice.
    • Write the real server-side Set-Cookie code for your own stack and test it against this model's reviewSessionCookie.

    In practice: moving an analytics dashboard's token out of localStorage

    NOTE

    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's staff dashboard at https://app.shop.example is a single-page app. After sign-in it stores a JSON Web Token in localStorage and sends it as a bearer header to https://api.shop.example. The page loads a third-party charting script and an analytics snippet. A security review flags the token store: any of those scripts, or an injection bug in a table showing customer-entered text, could read it. The token lives for 12 hours (illustrative), so a copied one is usable all day. Six engineers own the dashboard.

    Starting architecture

    Figure 6. Before the change

    Before: a long-lived token in localStorage, readable by every script on the dashboardStaff member to Dashboard app (uses); Dashboard app to localStorage (reads token); Third-party scripts to localStorage (can read it too); Dashboard app to API (Authorization header)ORIGIN APP.SHOP.EXAMPLEStaff memberStaff memberDashboard app: app.shop.exampleDashboard appapp.shop.examplelocalStorage: accessToken, 12 hlocalStorageaccessToken, 12 hThird-party scripts: charts, analyticsThird-partyscriptscharts, analyticsAPI: api.shop.exampleAPIapi.shop.exampleusesreads tokencan read it tooAuthorization header

    How to read this: the red arrow is the finding. Nothing separates the app's code from the third-party scripts that run in the same origin.

    Options considered

    Option What it fixes What it costs Risk
    Keep localStorage, shorten the token, add a Content Security Policy Smaller window, fewer scripts A refresh flow, a policy to maintain One missed script source exposes the token
    Memory token plus refresh through a backend Nothing persistent for script to read A silent refresh on every reload Injected script can still use the token while the page is open
    Same-site backend issues a __Host- session cookie No credential readable by script A backend on the dashboard's origin, a session store, CSRF defence CSRF becomes your responsibility

    The decision

    Field Decision record
    Context A 12-hour bearer token sits in localStorage on a page that runs third-party script.
    Decision Serve /api from the dashboard's own origin through a backend that holds the tokens. Issue one cookie, __Host-sid, with Path=/, Secure, HttpOnly, SameSite=Lax, no Domain, no Max-Age (session cookie). Require a custom request header on every state-changing call and make GET handlers free of side effects.
    Consequences, good Script cannot read the credential, there is no token to leak to logs or storage, and the server can revoke the session at once.
    Consequences, bad A session store to run, CSRF defences to keep, and the dashboard can no longer call the API from a different origin without a proxy.
    Revisit when The dashboard must be embedded in a partner site (cross-site, so SameSite=None and new CSRF analysis), or the session store becomes a scaling concern.

    Rollout and verification

    1. Review the cookie with the lab's reviewSessionCookie checklist before shipping.
    2. Dual-run. Accept both the old token and the new cookie for a week and count which each request uses.
    3. Test the negative cases: a cross-site POST is refused, the cookie is not sent over http:, and document.cookie does not list it.
    4. Remove the old token from localStorage for returning users, and revoke old tokens on the server.

    The 2 a.m. failure

    Two days after the cutover, support sees staff who open dashboard links from a chat tool landing on the sign-in page, although they are signed in. The sign-in redirect comes from the server: the dashboard's document request is checked for a session, and the cookie was missing from that request. The team had chosen SameSite=Strict in an earlier draft and the first release carried it. In the lab's section 6, a Strict cookie is not carried on a cross-site link click, but a Lax cookie is.

    First three checks: (1) reproduce by opening a dashboard link from another site and look at the request's Cookie header in the network panel; (2) compare the cookie's SameSite value with the incident; (3) find which route does the server-side session check on a document request. Mitigation: change the session cookie to SameSite=Lax, which carries it on top-level GET navigations, and confirm no GET endpoint changes state. Follow-up: keep the custom-header rule for writes, add a test that opens a link from another origin, and write the choice of Lax over Strict into the design record.

    Architect's notes

    • Write down who can read and who can send for every credential. If nobody can say which requests carry a cookie automatically, find out before shipping.
    • Prefer a backend that holds the tokens when you have one. It adds a session store and CSRF work, which are known problems with known defences.
    • Set every cookie attribute explicitly, in one helper that builds Set-Cookie, so review is easy and no browser default decides.
    • Keep sessions short and end them on the server. Short lifetimes limit a copied credential; revocation ends a stolen one.

    Common mistakes

    • A token in localStorage "because it persists". Persistence makes a stolen copy useful for longer.
    • Believing HttpOnly makes XSS harmless. It stops copying, not using.
    • Leaving SameSite unset, so the same cookie behaves differently for different users.
    • Setting Domain to share a cookie when a same-host backend would do.
    • Relying on Path for isolation, or SameSite=None without a CSRF plan.
    • Treating cookie deletion as logout, or putting state changes behind GET with a Lax cookie.
    • Credentials in URLs, which end up in logs and referrers.

    Key takeaways

    • A credential in the browser is a bearer value. Ask who can read it and when it is sent.
    • localStorage and sessionStorage are readable by any script on the origin: keep credentials out.
    • A cookie is sent by the browser. HttpOnly hides it from script, Secure keeps it off plain HTTP, SameSite limits cross-site sending, and no Domain keeps it host-only.
    • __Host- makes the browser refuse the cookie unless it is Secure, Path=/ and has no Domain.
    • HttpOnly stops theft, not use, and choosing a cookie means accepting a CSRF obligation.
    • Logging out is a server action. Default to a same-site backend that holds tokens.

    Practice exercises

    Exercise 1 — Starter (30 min): In your browser's developer tools for a site you run, list every cookie and storage entry. For each cookie note Secure, HttpOnly, SameSite, Domain and Path, and whether script can read it. Mark any that would fail reviewSessionCookie.

    Exercise 2 — Intermediate (2 hours): In the lab, add a test for a Strict cookie requested from a sibling subdomain (same site, different origin) and one for a __Host- cookie set with a Domain attribute. Predict each result before running it.

    Exercise 3 — Advanced (half day): Design the cookie behaviour for a dashboard that must also be embedded in an iframe on a partner site. Say which SameSite value the embedded session needs, what the browser may block regardless, and which CSRF defences you now need. Mark every claim you could not verify from a source.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments