Use cookies securely
Cookies must be set with Secure, HttpOnly, SameSite, and proper expiration. Learn cookie attributes and security best practices.
- 1
Cookie security attributes: Secure (only sent over HTTPS), HttpOnly (not accessible via JavaScript — prevents XSS theft), SameSite (Lax/Strict/None — controls cross-site sending, prevents CSRF), Domain (scope), Path (scope), Max-Age/Expires (lifetime), Partitioned (CHIPS — per-top-level-site). For session cookies: Secure + HttpOnly + SameSite=Lax + short Max-Age.
- 2 Base64 Encoder →
Encode cookie values as base64 if they contain binary data or special characters. This ensures the cookie value is a valid cookie string (no spaces, semicolons, or commas). The server decodes base64 to recover the original value. For JSON cookies, encode the JSON string as base64.
- 3 HMAC Generator →
Sign cookies with HMAC to prevent tampering. The cookie value is: data + "." + HMAC(secret, data). On receipt, verify the HMAC before trusting the data. This allows stateless session cookies — the session data is in the cookie (signed, not encrypted), and the server verifies the signature without a database lookup.
Frequently asked questions
- When to use HttpOnly?
- Always, for cookies that the browser needs but JavaScript does not (session IDs, CSRF tokens). HttpOnly prevents XSS from stealing the cookie via document.cookie. The only exception is cookies that JavaScript must read (e.g., a theme preference) — but these should not be security-sensitive.
- SameSite=Lax vs Strict vs None?
- Lax (default): cookies sent on top-level navigations (link clicks, form GET) but not on cross-site POST or iframes — prevents CSRF for most cases. Strict: cookies only sent for same-site requests — strongest but breaks cross-site links (user follows a link to your site, no cookies sent, appears logged out). None: always sent (requires Secure) — needed for third-party cookies (iframes, embeds).
Workflows that solve this
Learn more
Want to understand why?