Where should a single-page app store an authentication token, and what are the security trade-offs between localStorage and an httpOnly cookie?

technical-conceptual · Mid level · software-engineering

What the interviewer is really asking

Assesses understanding of token-storage threat models — XSS exposure of localStorage vs. CSRF exposure of cookies — and how to mitigate each.

What to say

What to avoid

Example answers

Strong: It's a trade between two attacks. localStorage is readable by any script, so a single XSS leaks the token. Cookies aren't readable if they're httpOnly, but they're sent automatically, which opens CSRF. I'd store the token in an httpOnly, Secure, SameSite cookie so JS can't exfiltrate it, then add SameSite and anti-CSRF protection for the auto-send risk. None of that excuses skipping XSS prevention or short token lifetimes.

Weak: I'd put the JWT in localStorage because it's simple to read on each request and attach to the Authorization header. As long as we're on HTTPS it's encrypted in transit, so it should be fine.

Want questions matched to your role? Paste a job title, job description, or CV and get a personalized set, or go Pro to unlock the full bank.