Cookie Security: HttpOnly, Secure, SameSite, and Best Practices

5 min read·Updated March 2026

HttpOnly: preventing JavaScript access

The HttpOnly flag prevents client-side JavaScript from reading the cookie. This is your primary defense against XSS-based session theft.

Without HttpOnly, if an attacker finds an XSS vulnerability on your site, they can run document.cookie to steal all cookies and send them to their server. With HttpOnly, the cookie is invisible to JavaScript — it's only sent with HTTP requests.

Rule: Always set HttpOnly on session cookies and authentication tokens. Only omit it for cookies that JavaScript legitimately needs to read (like theme preferences).

Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Lax; Path=/

Secure: HTTPS-only cookies

The Secure flag ensures the cookie is only sent over HTTPS connections. Without it, a cookie could be transmitted in plain text over HTTP, exposing it to network eavesdropping.

Rule: Set the Secure flag on every cookie in production. The only exception is during local development on localhost (which browsers treat as a secure context).

SameSite: CSRF protection

The SameSite attribute controls whether cookies are sent with cross-site requests. This is your defense against CSRF (Cross-Site Request Forgery) attacks.

  • SameSite=Strict — Cookie is never sent on cross-site requests. Most secure, but breaks legitimate flows like clicking a link from email to your logged-in site.
  • SameSite=Lax (recommended) — Cookie is sent on top-level navigations (clicking links) but not on cross-site sub-requests (images, iframes, AJAX). Good balance of security and usability.
  • SameSite=None; Secure — Cookie is sent on all cross-site requests. Required for third-party cookies (analytics, embeds). Must include the Secure flag.

Rule: Use SameSite=Lax for session cookies. Only use None if your cookie genuinely needs to work cross-site.

Tip

Modern browsers default to SameSite=Lax when no SameSite attribute is set. But don't rely on browser defaults — always set it explicitly for clarity and consistency.

Frequently Asked Questions

Related Articles

Was this helpful?

Check how your website performs in this area

Get Your Growth Score