Secure and HttpOnly Flags
What you'll learn: How two simple cookie flags dramatically reduce your session hijacking risk by controlling when and how cookies can be accessed.
The Problem
Session cookies are prime targets for attackers. If an attacker steals your session cookie, they can impersonate you completely. Two cookie attributes—Secure and HttpOnly—provide critical protection against the most common theft vectors.
The Secure Flag: HTTPS-Only Transmission
When you set the Secure flag on a cookie, the browser will only send it over encrypted HTTPS connections, never over plain HTTP.
Why this matters: Without the Secure flag, your session cookie can be transmitted in plaintext if a user accidentally visits http://yoursite.com instead of https://yoursite.com. Network attackers performing session sidejacking (sniffing network traffic) can easily intercept unencrypted cookies. The Secure flag prevents this entirely.
Analogy: It's like only sending sensitive mail via armored truck, never by bicycle courier on public roads.
The HttpOnly Flag: JavaScript Access Prevention
When you set the HttpOnly flag, JavaScript running in the browser cannot access the cookie via document.cookie or any DOM API.
Why this matters: If an attacker injects malicious JavaScript through XSS (Cross-Site Scripting), their first goal is usually stealing session cookies. With HttpOnly set, even successful XSS attacks cannot read the session cookie, blocking the most common session theft technique.
Analogy: It's like putting your valuables in a safe that only the bank teller (server) can open—customers (JavaScript) can't access it even if they're in the building.
Best Practice
Always use both flags together for session cookies:
Secureprotects against network-level attacksHttpOnlyprotects against client-side XSS attacks
Key Takeaway: The Secure flag ensures cookies only travel over encrypted connections, while HttpOnly prevents JavaScript access—together they provide essential defense-in-depth against session hijacking from both network and XSS attacks.