Course contentsShow
← Web Development
Lesson 1571 of 2,98229. Web Authentication PatternsFree lesson

Cookie Attributes for Security

Using HttpOnly, Secure, SameSite, and Domain attributes to protect authentication cookies.

Cookie Attributes for Security

What you'll learn: How to lock down authentication cookies using built-in security attributes that prevent common attack vectors.

Why Cookie Attributes Matter

When you store authentication session IDs in cookies, the browser automatically includes them with every request to your domain. This convenience becomes a security risk without proper safeguards. Cookie attributes act like padlocks and labels on your cookie, telling the browser exactly when and how to handle it.

Core Security Attributes

HttpOnly

Prevents JavaScript from accessing the cookie via document.cookie. Think of this as putting your cookie in a sealed envelope that only the browser's HTTP engine can open—not even your own JavaScript can peek inside.

Set-Cookie: sessionId=abc123; HttpOnly

This blocks XSS (Cross-Site Scripting) attacks where malicious scripts try to steal cookies.

Secure

Ensures the cookie only travels over HTTPS connections. Like sealing your envelope with tamper-evident tape, this prevents eavesdropping on unencrypted connections.

Set-Cookie: sessionId=abc123; Secure; HttpOnly

SameSite

Controls whether the cookie is sent with cross-site requests. It's your defense against CSRF (Cross-Site Request Forgery) attacks.

  • SameSite=Strict – Never send on cross-site requests
  • SameSite=Lax – Send only on top-level navigation (default in modern browsers)
  • SameSite=None – Always send (requires Secure)
Set-Cookie: sessionId=abc123; Secure; HttpOnly; SameSite=Strict

Domain

Limits which domains can receive the cookie. Omitting it restricts the cookie to the exact host that set it.

Set-Cookie: sessionId=abc123; Domain=example.com; Secure; HttpOnly

Key Takeaway: Always combine Secure, HttpOnly, and SameSite=Strict (or Lax) on authentication cookies to create defense-in-depth against XSS, man-in-the-middle, and CSRF attacks.