HttpOnly Cookies for Tokens
You'll learn how to store authentication tokens in HttpOnly cookies to block JavaScript access and prevent XSS-based token theft.
When you store tokens in localStorage or regular cookies, any JavaScript on your page can read them—including malicious scripts injected through XSS attacks. An HttpOnly cookie solves this by making the token completely invisible to JavaScript.
What Is an HttpOnly Cookie?
An HttpOnly cookie is a browser cookie with a special flag that forbids JavaScript from accessing it. It's like putting your house key in a lockbox that only the mail carrier (the browser) can open, not anyone who happens to walk by (JavaScript code).
When your server sets an HttpOnly cookie, it includes the HttpOnly attribute in the Set-Cookie header:
Set-Cookie: token=abc123xyz; HttpOnly; Secure; SameSite=Strict
The browser stores this token and automatically includes it with every request to your domain, but document.cookie cannot read or modify it.
How It Protects Against XSS
If an attacker injects malicious JavaScript into your page (XSS attack), their script cannot steal your token:
// This returns nothing for HttpOnly cookies
console.log(document.cookie); // ""
The token exists, travels with requests, but remains inaccessible to all JavaScript—good or bad.
The Trade-Off
You cannot manually attach HttpOnly cookies to requests (the browser does it automatically), so patterns like adding Authorization: Bearer <token> headers won't work. Your authentication must rely on cookie-based transmission instead.
Key Takeaway: HttpOnly cookies store tokens in a JavaScript-inaccessible space, automatically defending against XSS token theft while the browser handles transmission on every request.