Session & Cookie Best Practices
Cookies carrying session data are a frequent target, and several flags exist specifically to reduce that risk — flags that are trivial to set but frequently left at their permissive defaults.
Last updated 2026-09-08
Set the httpOnly flag on any cookie holding session or auth data
httpOnly prevents JavaScript from reading the cookie entirely, closing off theft via XSS — a compromised script on the page still can't exfiltrate the session cookie.
Set the Secure flag so cookies are only sent over HTTPS
Without Secure, a cookie can be transmitted over plain HTTP, exposing it to interception on an unencrypted connection — even if your site is normally served over HTTPS.
Set SameSite appropriately for your use case
SameSite=Strict offers the most CSRF protection but breaks cross-site navigation flows; SameSite=Lax is a reasonable default for most session cookies; SameSite=None (requiring Secure) is only for cookies that genuinely need to work across sites.
Set a reasonable expiration, not an indefinite one
A session cookie with no expiration or an extremely long one extends the window an attacker has to use a stolen cookie. Match expiration to how long a session genuinely should remain valid.
Regenerate the session ID after login
If a session ID exists before authentication and is reused after, an attacker who fixed that ID beforehand (session fixation) inherits the authenticated session. Issue a fresh session ID at the moment of successful login.
Common Mistakes to Avoid
- ⚠Session cookies without httpOnly, leaving them readable by any injected script
- ⚠No Secure flag, allowing the cookie to be sent over an unencrypted connection
- ⚠SameSite left at its default rather than explicitly chosen for the use case
- ⚠Reusing the pre-login session ID after authentication (session fixation)
- ⚠Session cookies with no expiration at all
Frequently Asked Questions
What's the practical difference between SameSite=Lax and Strict?
Lax still sends the cookie on top-level navigation (clicking a link) but not on cross-site requests like form POSTs or images; Strict never sends it cross-site at all, even on simple navigation — stronger, but can break legitimate cross-site links into your app.
Do I need httpOnly if I'm already using HTTPS?
Yes — HTTPS (Secure flag) protects the cookie in transit, but httpOnly protects it from a completely different threat: client-side script access via XSS. They address different risks and both matter.