Back to all terms
Securitybasic

HttpOnly & Secure Flags

Cookie attributes that prevent JavaScript access (HttpOnly) and restrict transmission to HTTPS (Secure), protecting against XSS and network interception.

Also known as: cookie security flags, HttpOnly flag, Secure flag, cookie attribute flags

Description

The HttpOnly and Secure flags are two fundamental cookie attributes that address distinct but complementary security concerns. The HttpOnly flag instructs the browser to prevent any client-side JavaScript from accessing the cookie through document.cookie, the Cookie Store API, or any other DOM mechanism. This is a critical defense against XSS attacks because even if an attacker manages to inject malicious JavaScript, they cannot exfiltrate HttpOnly cookies, protecting session tokens from theft.

The Secure flag ensures that the cookie is only transmitted over encrypted HTTPS connections. Without this flag, a cookie set over HTTPS could be sent in plaintext if the user is redirected to or visits the HTTP version of the site, or if a man-in-the-middle attacker forces a protocol downgrade. This protects session tokens and other sensitive cookie data from network-level eavesdropping.

While these flags are simple to implement, they are frequently overlooked. Many frameworks do not enable them by default for development convenience. It is essential to enable both flags for all cookies that contain session identifiers, authentication tokens, or any sensitive data. The only cookies that might reasonably omit HttpOnly are those that need to be read by client-side JavaScript, such as CSRF tokens in the double-submit pattern or user preference cookies -- and even then, the Secure flag should remain enabled.

Prompt Snippet

Set HttpOnly and Secure flags on all authentication and session cookies without exception. In Express: res.cookie('session', token, { httpOnly: true, secure: true, sameSite: 'lax' }). For cookie-based CSRF tokens that must be readable by JavaScript, omit HttpOnly but keep Secure. Audit all Set-Cookie headers in your application using browser DevTools or a security scanner (OWASP ZAP) to verify flags are present. Configure your session middleware (express-session, next-auth) to enforce these flags via its cookie options. In production, ensure secure: true is not conditionally disabled by NODE_ENV checks that may be misconfigured.

Tags

cookieshttponlysecure-flagsession-securityxss-mitigation