QA
Beginner LevelAuthentication & Authorization

What does the HttpOnly cookie flag do and why does it prevent XSS token theft?

❓ Interview Prompt: Explain browser DOM security boundaries, document.cookie API, Cross-Site Scripting (XSS), and HttpOnly cookie enforcement.

The 'HttpOnly' attribute is a security flag added to the 'Set-Cookie' HTTP response header that instructs the web browser that the cookie MUST NOT be exposed to client-side scripts.

Why HttpOnly Prevents XSS Token Theft:

•
If a token is stored in 'localStorage', 'sessionStorage', or a non-HttpOnly cookie, any successful Cross-Site Scripting (XSS) vulnerability allows an attacker's injected JavaScript snippet to execute:

'const stolenToken = document.cookie;' or 'localStorage.getItem('token')' and transmit it to an attacker's server!

•
When a cookie is marked 'HttpOnly', browser APIs ('document.cookie') return an empty string for that cookie, completely blocking malicious XSS scripts from reading the session token!

Code Implementation Example

typescript
// Setting HttpOnly session cookie header in HTTP response
res.setHeader('Set-Cookie', 
  'sessionId=s_992184; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=86400'
);

// Client-side JavaScript behavior:
// console.log(document.cookie); -> Does NOT contain sessionId!
💡Setting HttpOnly cookie flag blocking client-side JavaScript document.cookie access.
🎯 Interview Key Takeaway

HttpOnly blocks client-side JavaScript (document.cookie) from accessing cookies, protecting session tokens from XSS theft.

#HttpOnly#Cookies#XSS#Security#Beginner
Back to all Authentication & Authorization Questions→

More Authentication & Authorization Interview Questions

Beginner LevelAuthentication & Authorization

Compare JWT Token Authentication versus Stateful Sessions, and explain OAuth 2.0 PKCE flow.

Beginner LevelAuthentication & Authorization

What is the fundamental difference between Authentication (AuthN) and Authorization (AuthZ)?

Beginner LevelAuthentication & Authorization

Why should passwords never be stored in plain text and how do bcrypt and Argon2id work?