Course contentsShow
← Web Development
Lesson 803 of 2,98214. Browser StorageFree lesson

Secure and HttpOnly Flags

Learn the Secure flag for HTTPS-only cookies and HttpOnly for preventing JavaScript access to enhance security.

Secure and HttpOnly Flags

You'll learn how two cookie flags protect your data from network sniffing and malicious scripts.

What These Flags Do

Cookies can carry sensitive information like session tokens. Two special flags add critical layers of security:

The Secure flag ensures a cookie is only sent over HTTPS connections, never plain HTTP. Think of it like requiring an armored truck instead of a regular van for transporting valuables—the cookie travels only through encrypted channels, protecting it from eavesdroppers on the network.

The HttpOnly flag prevents JavaScript from accessing the cookie through document.cookie. This shields your cookie from cross-site scripting (XSS) attacks where malicious scripts try to steal session data. It's like putting your valuables in a vault that only the server (not client-side code) can open.

Setting These Flags

You add these flags when setting cookies by appending them as attributes:

// Secure flag - only sent over HTTPS
document.cookie = "sessionToken=abc123; Secure";

// HttpOnly flag - cannot be set via JavaScript!
// (Must be set by server, not document.cookie)

// Combining flags with other attributes
document.cookie = "authToken=xyz789; Path=/; Max-Age=3600; Secure";

Important limitation: You cannot set HttpOnly from JavaScript—that's the point! It must be set by your web server in HTTP response headers. This prevents malicious scripts from removing the protection.

When to Use Them

  • Use Secure for any cookie on production sites (which should always use HTTPS)
  • Use HttpOnly for authentication tokens and session IDs that JavaScript doesn't need to read
  • Combine both for maximum security on sensitive cookies

Key Takeaway: The Secure flag protects cookies in transit by requiring HTTPS, while HttpOnly protects them from JavaScript access—together they form essential defenses against common web attacks.