Compares cookies, localStorage, sessionStorage (and briefly IndexedDB) on scope, lifetime, size limits, automatic sending, JavaScript access and XSS/CSRF exposure, covers cookie attributes and the __Host- prefix, and maps each to safe uses such as session cookies, preferences and drafts.
Cookies are small (about 4 KB each) name/value pairs the browser sends automatically with every matching request; with HttpOnly JavaScript can't read them, with Secure they only travel over HTTPS, and SameSite controls whether they go on cross-site requests. localStorage is a per-origin key/value store (about 5 MB) that persists until cleared and is never sent to the server; sessionStorage is the same but scoped to one tab and cleared when it closes. Both are readable by any script on the origin, so an XSS bug exposes everything in them. Rule of thumb: put the session in an HttpOnly, Secure, SameSite cookie, keep only non-sensitive UI state (theme, draft form, last filter) in Web Storage. The trade-off: cookies resist XSS theft but invite CSRF; storage avoids CSRF but is wide open to XSS.
"The difference that matters most is who can read it and when it's sent. Cookies are set by the server with
Set-Cookie(or by JavaScript), and the browser attaches them to every request whose domain and path match. That automatic sending is what makes them perfect for sessions and also what makes CSRF possible. Marking a cookieHttpOnlyhides it fromdocument.cookie, so even an XSS bug can't exfiltrate it;Securekeeps it off plain HTTP; andSameSite=Lax, now the default in Chromium when you don't set it, stops it riding along on cross-site POSTs.localStorage and sessionStorage are the Web Storage API: synchronous string key/value stores of roughly 5 MB per origin. Neither is ever sent to the server, so they're CSRF-proof by nature, but any script running on the origin, including a compromised npm package or an injected script, can read all of it. localStorage persists across tabs and restarts; sessionStorage lives only as long as the tab and isn't shared between tabs. For anything bigger or structured there's IndexedDB, which is asynchronous.
So my defaults are: the authentication session lives in an
HttpOnly; Secure; SameSite=Laxcookie, ideally with the__Host-prefix so it's locked to one host; ASP.NET Core's cookie authentication does exactly that and encrypts the content with Data Protection. Web Storage holds only things I'd be fine leaking: theme, collapsed panels, a draft comment. The mistake I see is putting a JWT access token and the user's profile in localStorage because it's easy. Under the Privacy Act, personal information sitting in readable storage on shared or compromised machines is a breach waiting to happen, and an XSS bug turns it into account takeover."
| Cookie | localStorage | sessionStorage | |
|---|---|---|---|
| Scope | Domain + path (+ SameSite rules) | Origin | Origin + tab |
| Lifetime | Session or Expires/Max-Age |
Until cleared | Until tab closes |
| Size | ~4 KB each, ~180 per domain (varies) | ~5 MB per origin | ~5 MB per origin |
| Sent to server | Automatically | Never | Never |
| JS access | Yes, unless HttpOnly |
Yes | Yes |
| API | Set-Cookie, document.cookie, Cookie Store API |
Sync getItem/setItem |
Same |
| Main risk | CSRF | XSS theft | XSS theft |
| Attribute | Effect |
|---|---|
HttpOnly |
Not visible to JavaScript |
Secure |
Only sent over HTTPS |
SameSite=Strict |
Never sent on cross-site requests |
SameSite=Lax |
Sent on top-level GET navigations only, cross-site |
SameSite=None |
Always sent (requires Secure) |
Domain |
Omit = this host only; set = host and subdomains |
Path |
URL path prefix it applies to |
__Host- prefix |
Requires Secure, Path=/, no Domain |
| Data | Store in |
|---|---|
| Auth session | HttpOnly Secure SameSite cookie |
| Antiforgery request token | Readable cookie or page, sent back in a header |
| Theme, language, UI layout | localStorage |
| Multi-step form in one tab | sessionStorage |
| Offline data, large lists | IndexedDB (encrypt nothing sensitive client-side expecting safety) |
| Access tokens, personal data | Not in Web Storage: keep server-side (BFF) |
A customer portal stored the access token and the user's date of birth and address in localStorage. A penetration test found a stored XSS in a support-ticket field that read both in one line of script. Moving to a cookie session via a BFF and clearing storage on release meant the same XSS could no longer take tokens, and the finding dropped from critical to medium.
Checks that the candidate chooses browser storage from a security and lifetime point of view rather than convenience.
Green flags
__Host- prefixRed flags
Server -> Set-Cookie: __Host-sid=abc; Path=/; Secure; HttpOnly; SameSite=Lax
Browser cookie jar: { host: app.example.com.au, name: __Host-sid, ... }
Later request to https://app.example.com.au/api/orders
-> browser matches host, path, Secure, SameSite
-> Cookie: __Host-sid=abc
The browser decides on every request. JavaScript only sees the cookie through document.cookie if it isn't HttpOnly.
Site = scheme + registrable domain (eTLD+1). app.example.com.au and api.example.com.au are same-site (both example.com.au, using the public suffix list where com.au is a suffix) but cross-origin. SameSite rules use site; CORS and Web Storage use origin. That's why a cookie can flow between subdomains while localStorage is separate for each.
Storage is per origin and partitioned by browser profile. Calls are synchronous and hit disk, so big writes on the main thread can jank the page. The storage event fires in other tabs when localStorage changes, which is handy for syncing logout across tabs. Private browsing and Safari's tracking prevention may cap or clear storage (Safari can delete script-written storage after 7 days without interaction).
Cookies and storage inside cross-site iframes are increasingly partitioned (keyed by top-level site) or blocked. Safari and Firefox block third-party cookies by default; Chrome supports partitioned cookies (Partitioned attribute, CHIPS). Designs relying on third-party cookies for login in an embedded iframe are fragile.
XSS can't read an HttpOnly cookie, but it can still use it by making requests from the victim's page. So HttpOnly limits the blast radius (no token theft for later use elsewhere) while CSP and output encoding prevent the XSS itself.
Response.Cookies.Append and each attribute, and confirm document.cookie can't see it when HttpOnly.storage event in the other.__Host- cookie with a Domain attribute and watch the browser reject it.Setting a hardened cookie in ASP.NET Core, and safe Web Storage use in the browser.
// Program.cs (.NET 10)
using Microsoft.AspNetCore.Authentication.Cookies;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(o =>
{
o.Cookie.Name = "__Host-sid"; // host-locked: Secure, Path=/, no Domain
o.Cookie.HttpOnly = true; // invisible to JavaScript
o.Cookie.SecurePolicy = CookieSecurePolicy.Always;
o.Cookie.SameSite = SameSiteMode.Lax; // not sent on cross-site POSTs
o.ExpireTimeSpan = TimeSpan.FromHours(8);
o.SlidingExpiration = true;
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
// A non-sensitive preference cookie that JS may read
app.MapPost("/api/prefs/theme/{theme}", (string theme, HttpResponse res) =>
{
res.Cookies.Append("theme", theme, new CookieOptions
{
Secure = true, SameSite = SameSiteMode.Lax, HttpOnly = false, MaxAge = TimeSpan.FromDays(365), Path = "/"
});
return TypedResults.NoContent();
});
app.Run();
// Browser: Web Storage for non-sensitive UI state only
export function saveDraft(ticketId: string, text: string) {
sessionStorage.setItem(`draft:${ticketId}`, text); // per tab, gone when the tab closes
}
export function loadTheme(): 'light' | 'dark' {
return localStorage.getItem('theme') === 'dark' ? 'dark' : 'light'; // validate: storage is just strings
}
// Sync logout across tabs: other tabs receive the storage event
window.addEventListener('storage', (e) => {
if (e.key === 'logout') window.location.assign('/signed-out');
});
export function broadcastLogout() {
localStorage.setItem('logout', Date.now().toString());
}
Secure or HttpOnly on the session cookie. Why it is wrong: It can leak over HTTP or to XSS. Instead: __Host- prefix with Secure and HttpOnly.Domain=example.com.au by habit. Why it is wrong: Every subdomain, including a forgotten marketing site, receives the cookie. Instead: Omit Domain unless sharing is required.Storage choice is really a threat-model choice: cookies are exposed to CSRF, which is well understood and largely solved by SameSite plus antiforgery, while Web Storage is exposed to XSS, which is harder to eliminate completely in a big SPA with hundreds of npm dependencies. That asymmetry is why current guidance (the IETF OAuth browser-based apps BCP) prefers keeping tokens out of JavaScript altogether.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| HttpOnly cookie session | Auth for your own web app | CSRF defences; same-site design | Third-party APIs called directly from JS |
| localStorage | Preferences, cached non-sensitive data | XSS-readable, sync API | Tokens, personal data |
| sessionStorage | Per-tab drafts and wizards | Lost on tab close | Cross-tab state |
| IndexedDB | Offline, large data | Async API complexity | Secrets |
To measure, run an automated scan (e.g. OWASP ZAP or a Playwright check) that fails CI if localStorage contains keys matching token or a JWT pattern, and audit cookie flags in the Application panel during each release.
SameSite tells the browser whether to send a cookie on cross-site requests. Strict: never cross-site. Lax: cross-site only on top-level GET navigations (clicking a link), not on cross-site POSTs, iframes or fetch. None: always, and it must also be Secure. 'Site' means scheme plus registrable domain, so app.example.com.au and api.example.com.au are the same site.
Chromium now treats cookies without the attribute as Lax by default, which broke flows that relied on cross-site POSTs, most famously OpenID Connect form_post callbacks: the identity provider POSTs back to /signin-oidc, so the correlation and nonce cookies must be SameSite=None; Secure, which ASP.NET Core sets for you over HTTPS. The trade-off: Strict is safest but hurts UX; None is needed for embedding and federation but loses CSRF protection.
A refresh token lets a client get new short-lived access tokens without asking the user to sign in again. Because it is long-lived, it is the most valuable token to steal.
HttpOnly, Secure, SameSite cookie.The trade-off: a BFF adds a server hop and session state, in exchange for tokens that never reach the browser.
After a successful login the app calls HttpContext.SignInAsync: the cookie handler serialises the ClaimsPrincipal into an authentication ticket, encrypts and signs it with Data Protection, and sends it as a cookie. On each request the handler decrypts the cookie and rebuilds HttpContext.User, with no database call.
HttpOnly (JavaScript can't read it), Secure (HTTPS only), SameSite=Lax by default (not sent on most cross-site requests).ExpireTimeSpan (default 14 days) with sliding expiration that reissues the cookie once half the window has passed; IsPersistent decides whether it survives closing the browser.The trade-off: a self-contained cookie is fast and stateless, but you can't revoke it without extra checks or a server-side ticket store.
Last updated 23 Nov 2026.