HTTP-Only Cookies for JWT Storage
You'll learn: How to store JWTs in HTTP-only cookies to protect them from JavaScript-based attacks while maintaining secure authentication.
The Problem with localStorage
In the previous lesson, you learned that storing JWTs in localStorage or sessionStorage exposes them to XSS (Cross-Site Scripting) attacks. Any malicious JavaScript that runs on your page can access these storage mechanisms and steal your tokens.
What Are HTTP-Only Cookies?
HTTP-only cookies are special cookies that have an httpOnly flag set to true. This flag makes the cookie completely inaccessible to JavaScript—you can't read it with document.cookie or any other client-side code.
Think of it like a sealed envelope that only the mail carrier (browser) can handle during delivery (HTTP requests). No one standing nearby (malicious scripts) can open it and read what's inside.
How It Works
When your server creates a JWT after successful login, instead of sending it in the response body for client-side storage, it sends it as an HTTP-only cookie:
Set-Cookie: token=eyJhbGc...; HttpOnly; Secure; SameSite=Strict
The browser automatically attaches this cookie to every subsequent request to your server. Your client-side JavaScript never touches or even sees the JWT—the browser handles everything automatically.
The Security Advantage
Because JavaScript cannot access HTTP-only cookies, even if an attacker injects malicious code into your site, they cannot steal the JWT. This dramatically reduces your XSS attack surface while still maintaining stateless authentication benefits.
Key Takeaway: HTTP-only cookies prevent JavaScript from accessing JWTs, making them significantly more secure than localStorage for token storage, though they require server-side cookie handling and won't work for cross-domain requests without CORS configuration.