HttpOnly Cookies for Token Storage
What you'll learn: How HttpOnly cookies protect authentication tokens from JavaScript-based XSS attacks by making them invisible to client-side code.
The Core Problem and Solution
You've learned that localStorage is vulnerable to XSS attacks because any malicious JavaScript can read it with localStorage.getItem('token'). HttpOnly cookies solve this by storing tokens in cookies that the browser automatically attaches to requests, but which JavaScript cannot read or modify.
When a cookie is marked HttpOnly, the browser enforces a strict rule: no JavaScript code—whether legitimate or malicious—can access that cookie through document.cookie. Even if an attacker injects a script, they cannot steal the token.
How It Works
The server sets an HttpOnly cookie in its response:
Set-Cookie: authToken=abc123xyz; HttpOnly; Secure; SameSite=Strict
From the frontend's perspective, you don't manually handle the token at all. The browser automatically:
- Stores the cookie securely
- Sends it with every request to the same domain
- Blocks any JavaScript access attempts
Your frontend code makes authenticated requests normally:
// No token in headers needed!
fetch('/api/user/profile', {
credentials: 'include' // Tells browser to include cookies
});
The XSS Defense Advantage
If an attacker injects malicious JavaScript, they might try:
// This returns empty string - HttpOnly cookies are invisible!
console.log(document.cookie);
The token simply isn't accessible. The attacker cannot exfiltrate it via XSS, dramatically reducing the attack surface you learned about with localStorage vulnerabilities.
Key Takeaway: HttpOnly cookies prevent XSS-based token theft by making tokens completely inaccessible to JavaScript while still allowing the browser to automatically include them in requests—combining security with convenience.