HttpOnly cookies are more secure than localStorage for storing authentication tokens because they are inaccessible to JavaScript, mitigating XSS attacks, but require CSRF protection.
localStorage is vulnerable to XSS because any injected script can read the token and exfiltrate it. HttpOnly cookies cannot be read by JavaScript, preventing XSS token theft. However, cookies are automatically sent with every request, making them susceptible to CSRF unless mitigated (e.g., SameSite=Strict, CSRF tokens). For SPAs, using HttpOnly cookies with SameSite=Strict and a CSRF token provides the best security. localStorage is simpler but riskier, especially for high-value applications.
localStorage: Accessible via JavaScript → XSS risk. No CSRF risk (since token sent manually in Authorization header).
HttpOnly cookie: Not accessible via JavaScript → XSS safe. Requires CSRF protection (SameSite, CSRF tokens).
Recommendation: Use HttpOnly cookies with SameSite=Strict and short-lived tokens. For SPAs, combine with backend authentication.