Course contentsShow
← Web Development
Lesson 2931 of 2,98252. Frontend SecurityFree lesson

Secure Cookies: Secure and SameSite Flags

Set cookie attributes to ensure they're only transmitted over HTTPS and protected from CSRF.

Secure Cookies: Secure and SameSite Flags

You'll learn how to properly configure cookie attributes to ensure they're only transmitted over HTTPS and protected from CSRF attacks.

Why Cookie Flags Matter

Cookies are like digital sticky notes your browser passes back and forth with servers. Without proper configuration, these notes can be intercepted by attackers on insecure connections or stolen by malicious sites. Two critical attributes—Secure and SameSite—protect your cookies from these threats.

The Secure Flag

The Secure flag ensures cookies are only sent over HTTPS connections, never plain HTTP. Think of it as requiring an armored truck instead of a bicycle to transport valuables. If someone intercepts the connection, they won't see your cookie data traveling in the clear.

When setting a cookie from your server, add the Secure attribute:

Set-Cookie: sessionId=abc123; Secure; Path=/; Max-Age=3600

Without this flag, cookies can leak over unencrypted connections—even if your site uses HTTPS, a single insecure resource could expose them.

The SameSite Flag

The SameSite attribute prevents cookies from being sent with cross-site requests, defending against CSRF attacks. It has three values:

  • Strict: Never send cookies on cross-site requests (most secure)
  • Lax: Send cookies on safe cross-site navigations (like clicking links)
  • None: Allow cross-site cookies (requires Secure flag)
Set-Cookie: authToken=xyz789; Secure; SameSite=Strict; Path=/

SameSite=Strict means if a malicious site tries to trick your browser into making a request to your app, the authentication cookie won't be included—blocking the CSRF attack.

Key Takeaway: Always set Secure to protect cookies in transit and configure SameSite (preferably Strict or Lax) to prevent CSRF attacks—these two flags are your cookie security foundation.