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

SameSite Cookie Attribute for CSRF Protection

Learn how SameSite=Strict and SameSite=Lax prevent cross-site request forgery with cookie-based tokens.

SameSite Cookie Attribute for CSRF Protection

What you'll learn: How the SameSite cookie attribute blocks cross-site request forgery attacks by controlling when browsers send cookies with requests.

The Core Idea

The SameSite attribute tells browsers whether to include cookies when requests originate from different sites. Think of it like a security guard checking visitor badges: "Did you start your journey from inside this building, or from outside?" If a malicious site tries to trick your browser into making authenticated requests to your banking app, SameSite can refuse to send your session cookie along.

SameSite Values

SameSite=Strict is the strictest setting. Cookies are only sent when the request originates from the same site as the cookie's domain. If you click a link to yourbank.com from evil.com, your session cookie won't be sent—even for top-level navigation. This completely prevents CSRF but can break legitimate flows like clicking email links.

SameSite=Lax (now browser default) is more permissive. Cookies are sent with "safe" top-level navigation (clicking links, GET requests) but not with cross-site POST requests or embedded requests (images, iframes). This blocks most CSRF attacks while preserving user experience for legitimate navigation.

SameSite=None disables protection entirely (requires Secure flag).

Setting the Attribute

// Server-side cookie setting
Set-Cookie: sessionId=abc123; SameSite=Strict; Secure; HttpOnly

// Or for token cookies
Set-Cookie: authToken=xyz789; SameSite=Lax; Secure; HttpOnly

The SameSite attribute works alongside HttpOnly (prevents XSS access) to create defense-in-depth. Together, they protect your authentication tokens from both cross-site and same-site attacks.

Key Takeaway: SameSite=Strict blocks all cross-site cookie transmission for maximum CSRF protection, while SameSite=Lax balances security with usability by allowing safe top-level navigation while blocking dangerous cross-site requests.