📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Where should a web app keep data in the browser? Compare cookies, localStorage and sessionStorage on scope, lifetime, size, whether they're sent to the server automatically and whether JavaScript can read them. Explain the HttpOnly, Secure, SameSite, Domain and Path attributes, and say what each storage option is and isn't safe for.

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.

Intermediate Theory Intermediate browser-security cookies frontend localstorage sessionstorage web-storage

🎯 Key points

  • Cookies are sent automatically with matching requests; Web Storage never is
  • HttpOnly cookies can't be read by JavaScript, so XSS can't steal them (but can still use them from the page)
  • localStorage: per origin, persists until cleared, ~5 MB, synchronous, readable by any script on the origin
  • sessionStorage: per origin and per tab, cleared when the tab closes
  • Secure (HTTPS only), Domain (omit = host only), Path, Expires/Max-Age; __Host- prefix locks a cookie to one host
  • SameSite: Lax (Chromium default) suits most sessions; Strict for high-risk apps with no inbound cross-site links; None needs Secure
  • Never store tokens or personal data in localStorage (APP 11: take reasonable steps to protect personal information)
  • Same-site (eTLD+1) drives SameSite; same-origin drives CORS and storage; third-party cookies/storage are increasingly partitioned or blocked

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 cookie HttpOnly hides it from document.cookie, so even an XSS bug can't exfiltrate it; Secure keeps it off plain HTTP; and SameSite=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=Lax cookie, 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."


Side-by-side

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

Cookie attributes

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

What goes where

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)

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate chooses browser storage from a security and lifetime point of view rather than convenience.

Green flags

  • States cookies are sent automatically and storage never is
  • Explains HttpOnly, Secure, SameSite and the __Host- prefix
  • Maps XSS risk to storage and CSRF risk to cookies
  • Refuses to store tokens or personal data in localStorage

Red flags

  • Puts JWTs in localStorage by default
  • Confuses sessionStorage with server-side session
  • Thinks HttpOnly prevents XSS

📚 Learn in depth

1. How cookies flow

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.

2. Same-site vs same-origin

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.

3. Web Storage internals

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).

4. Third-party contexts and partitioning

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.

5. Why HttpOnly isn't a complete answer

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.

Try it yourself

  1. Open DevTools → Application → Cookies and Local Storage on a site you use; note which cookies are HttpOnly.
  2. Set a cookie from ASP.NET Core with Response.Cookies.Append and each attribute, and confirm document.cookie can't see it when HttpOnly.
  3. Open two tabs, write to localStorage in one and log the storage event in the other.
  4. Write to sessionStorage, duplicate the tab and observe that the copy is cloned, then diverges.
  5. Try setting a __Host- cookie with a Domain attribute and watch the browser reject it.

💻 Code

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());
}

⚠ Common mistakes

  • Mistake: Storing access or refresh tokens in localStorage. Why it is wrong: Any XSS or malicious dependency reads and exfiltrates them for use anywhere. Instead: Keep tokens server-side and use an HttpOnly cookie session (BFF).
  • Mistake: Storing personal information (address, DOB, Medicare number) in Web Storage. Why it is wrong: It persists on shared devices and is readable by scripts; a Privacy Act/APP 11 risk. Instead: Fetch it when needed; keep it server-side.
  • Mistake: Omitting 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.
  • Mistake: Setting 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.
  • Mistake: Assuming SameSite=Lax removes the need for antiforgery. Why it is wrong: Same-site subdomains and GET side effects still get through. Instead: Use antiforgery tokens for state-changing requests.
  • Mistake: Putting large data in cookies. Why it is wrong: It's sent with every request, bloating headers and hitting the 4 KB limit. Instead: Keep cookies small; store state server-side.
  • Mistake: Trusting values read back from storage. Why it is wrong: Users and scripts can edit them. Instead: Validate and treat as untrusted input.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions SameSite Lax, Strict or None Why: Checks deeper understanding of SameSite and what counts as the same site
    How to answer

    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.

  2. When: Candidate says tokens should not live in localStorage Why: Checks token storage, refresh rotation and the BFF pattern
    How to answer

    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.

    • Rotation: every refresh returns a new refresh token and invalidates the old one. Reuse detection: if an old one is used again, someone has a copy, so the server revokes the whole token family.
    • Lifetimes: access tokens 5–15 minutes; refresh tokens bounded by an idle timeout and an absolute session limit.
    • Storage: in a SPA, anything JavaScript can read, XSS can steal. The BFF pattern keeps tokens on the server and gives the browser only an 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.

  3. When: Candidate mentions ASP.NET Core cookie authentication Why: Checks what is inside the auth cookie and Data Protection's role
    How to answer

    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.

    • Flags: HttpOnly (JavaScript can't read it), Secure (HTTPS only), SameSite=Lax by default (not sent on most cross-site requests).
    • Expiry: 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.
    • Keys: every instance must share the Data Protection key ring, or cookies issued by one server can't be read by another.

    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.

More in Web Basics

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me