Cookie Security: HttpOnly, Secure, SameSite and Beyond
Secure your cookies against theft and misuse. Learn the essential cookie attributes, understand SameSite policies, and implement defense-in-depth for session management.

Cookies are the backbone of web authentication. They store session identifiers, authentication tokens, and user preferences. Insecure cookies are a prime target for attackers seeking to hijack user sessions or steal sensitive data. This guide covers essential cookie security attributes and best practices.
Cookie Security Attributes
The Secure Attribute
Cookies with the Secure attribute are only sent over HTTPS connections:
Set-Cookie: sessionId=abc123; Secure
Why it matters: Without Secure, cookies are sent over HTTP, where they can be intercepted by network attackers (coffee shop WiFi, corporate proxies, ISPs).
Always use Secure for:
- Session identifiers
- Authentication tokens
- Any sensitive data
The HttpOnly Attribute
Cookies with HttpOnly cannot be accessed by JavaScript:
Set-Cookie: sessionId=abc123; HttpOnly
Why it matters: XSS attacks often try to steal cookies via document.cookie. HttpOnly prevents this, limiting XSS impact.
Always use HttpOnly for:
- Session identifiers
- Authentication tokens
- Any cookie JavaScript doesn't need to read
Exception: CSRF tokens sometimes need JavaScript access for AJAX requests. Consider alternatives like custom headers.
The SameSite Attribute
SameSite controls when cookies are sent with cross-site requests:
SameSite=Strict
Set-Cookie: sessionId=abc123; SameSite=Strict
Cookie is never sent with cross-site requests. Best protection against CSRF but may break legitimate cross-site navigation.
SameSite=Lax (Default in modern browsers)
Set-Cookie: sessionId=abc123; SameSite=Lax
Cookie is sent with top-level navigations (clicking links) but not with embedded requests (images, iframes, AJAX). Good balance of security and usability.
SameSite=None
Set-Cookie: sessionId=abc123; SameSite=None; Secure
Cookie is sent with all cross-site requests. Required for legitimate cross-site use cases but requires Secure attribute. Opens door to CSRF if not handled carefully.
Cookie Prefixes
Cookie prefixes provide additional security guarantees enforced by browsers:
__Secure- Prefix
Set-Cookie: __Secure-sessionId=abc123; Secure; Path=/
Cookie must have Secure attribute and be set over HTTPS. Prevents HTTP attackers from setting secure cookies.
__Host- Prefix
Set-Cookie: __Host-sessionId=abc123; Secure; Path=/
Cookie must have Secure, must not have Domain, and must have Path=/. Prevents subdomain attacks and is the strongest prefix.
When to Use Prefixes
- __Host-: Session cookies on your main domain
- __Secure-: Cookies that need subdomain sharing
Domain and Path Scoping
The Domain Attribute
Set-Cookie: token=abc; Domain=example.com
When set, cookie is sent to example.com AND all subdomains (api.example.com, blog.example.com).
Security consideration: If any subdomain is compromised, it can read and potentially overwrite cookies. Omit Domain when possible:
Set-Cookie: token=abc // Only sent to exact origin
The Path Attribute
Set-Cookie: token=abc; Path=/admin
Cookie only sent to /admin and sub-paths. However, this is NOT a security boundary—JavaScript on /public can still access /admin cookies in some scenarios.
Cookie Expiration
Session Cookies
Set-Cookie: sessionId=abc123
No expiration = session cookie. Deleted when browser closes (but browsers often restore sessions).
Persistent Cookies
Set-Cookie: sessionId=abc123; Max-Age=86400
Set-Cookie: sessionId=abc123; Expires=Thu, 01 Jan 2026 00:00:00 GMT
Best practice: Set reasonable expiration times. Long-lived session cookies increase the window for theft. Consider:
- Session cookies: Use session (no expiry) or short Max-Age
- "Remember me": Longer expiry, but use a separate token with device binding
- Sliding expiration: Extend on each request
Complete Secure Cookie Examples
Session Cookie
Set-Cookie: __Host-sessionId=abc123; Secure; HttpOnly; SameSite=Lax; Path=/
Remember Me Token
Set-Cookie: __Secure-rememberMe=xyz789; Secure; HttpOnly; SameSite=Lax; Max-Age=2592000; Path=/
CSRF Token (needs JS access)
Set-Cookie: __Secure-csrfToken=def456; Secure; SameSite=Strict; Path=/
Cross-Site Cookie (third-party context)
Set-Cookie: __Secure-widgetSession=ghi789; Secure; HttpOnly; SameSite=None; Path=/
Framework Implementation
Express.js
app.use(session({
name: '__Host-sessionId',
secret: process.env.SESSION_SECRET,
cookie: {
secure: true,
httpOnly: true,
sameSite: 'lax',
maxAge: 24 * 60 * 60 * 1000, // 24 hours
path: '/'
},
resave: false,
saveUninitialized: false
}));
Next.js API Route
export default function handler(req, res) {
res.setHeader('Set-Cookie', [
`__Host-sessionId=${sessionId}; Secure; HttpOnly; SameSite=Lax; Path=/`
]);
res.json({ success: true });
}
Django
# settings.py
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = 'Lax'
SESSION_COOKIE_NAME = '__Host-sessionid'
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_SAMESITE = 'Strict'
Common Cookie Vulnerabilities
Session Fixation
Attack: Attacker sets a known session ID before victim authenticates.
Prevention: Always regenerate session ID on login.
Cookie Tossing
Attack: Subdomain sets cookie that shadows parent domain cookie.
Prevention: Use __Host- prefix or be careful with Domain attribute.
Cookie Overflow
Attack: Attacker creates many cookies to push out security cookies.
Prevention: Use __Host- prefix (path-locked) and monitor for anomalies.
Cookie Security Checklist
- Set
Secureon all cookies in production - Set
HttpOnlyon cookies JavaScript doesn't need - Set
SameSite=LaxorStrictappropriately - Use
__Host-prefix for session cookies - Use
__Secure-prefix for other sensitive cookies - Omit
Domainattribute when subdomain access isn't needed - Set reasonable
Max-Age/Expiresvalues - Regenerate session IDs after authentication
- Use SecScanner to audit cookie security attributes
- Monitor for suspicious cookie patterns
Proper cookie security is fundamental to web application security. These attributes work together to create defense in depth. Implement all of them for robust session protection.
Related Articles
Check Your Website Security
Want to see how your website measures up? Run a free security scan with SecScanner to identify vulnerabilities and get actionable remediation guidance.
Scan Your Website Free