How to Set the Secure, HttpOnly and SameSite Cookie Attributes
By the IDEAVALU team · Updated
If someone steals the cookie that keeps a user signed in, they can act as that user without a password. Three attributes close off most of the ways a cookie gets stolen.
What the three attributes do
Each one closes a different path.
- Secure: the cookie is sent only over encrypted HTTPS connections.
- HttpOnly: JavaScript cannot read the cookie, so an XSS bug cannot easily steal it.
- SameSite: decides whether the cookie is sent with requests that come from other sites. With Lax, form posts from other sites do not carry the cookie, which helps prevent CSRF.
Check it yourself
In developer tools, open Application (Storage in Firefox) and then Cookies to see the Secure, HttpOnly and SameSite columns for each cookie. With curl, show the Set-Cookie headers.
Show Set-Cookie
curl -sI https://example.com | grep -i set-cookie
How to fix
Cookie attributes
Add Secure, HttpOnly and SameSite to cookies.
Next.js (Route Handler / Server Action)
const cookieStore = await cookies()
cookieStore.set('session', value, {
secure: true,
httpOnly: true,
sameSite: 'lax',
path: '/',
})Make every cookie HttpOnly unless JavaScript must read it (display settings and the like). Login tokens in localStorage or in cookies without HttpOnly can be stolen through XSS.
FAQ
- Can I store login tokens in localStorage?
- JavaScript can read localStorage, so an XSS bug can steal tokens stored there. Use an HttpOnly cookie where you can, and follow your auth library's recommended storage (for example Supabase's).