TL;DR
Cookies are small pieces of data stored in the browser and sent with every request to the same domain. They're used for sessions, authentication, and preferences. For security, use httpOnly (blocks JavaScript access), Secure (HTTPS only), and SameSite (prevents CSRF). Don't store sensitive data directly in cookies; use them for session IDs instead.
The Simple Explanation
When you log in, the server sets a cookie with your session ID. Your browser stores it and automatically sends it with every request to that domain. The server reads the cookie to know who you are. It's like a wristband at an event. Show it, and you get access without re-verifying.
Cookie Attributes
Set-Cookie: session_id=abc123; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=3600
| Attribute | Purpose | Recommendation |
|---|---|---|
| HttpOnly | Block JavaScript access | Always for auth cookies |
| Secure | HTTPS only | Always in production |
| SameSite | Prevent CSRF | Strict or Lax |
| Path | URL path scope | Use / or specific path |
| Max-Age | Expiration in seconds | Set appropriate timeout |
Cookies vs Other Storage
| Feature | Cookies | localStorage | sessionStorage |
|---|---|---|---|
| Size limit | 4KB | 5MB | 5MB |
| Sent with requests | Yes, automatically | No | No |
| JS access block | httpOnly option | No | No |
| Expiration | Configurable | Never | Tab close |
Security Best Practices
- Session cookies: Always httpOnly + Secure + SameSite
- Don't store secrets: Use session IDs, not actual data
- Set expiration: Don't let sessions last forever
- Domain restriction: Only set cookies for your domain
- Delete on logout: Clear cookies when user logs out
localStorage is not secure for tokens. Any JavaScript on your page (including malicious XSS) can read localStorage. Use httpOnly cookies for session tokens to prevent theft.
What is the difference between cookies and localStorage?
Cookies are automatically sent with every HTTP request to the same domain. localStorage is not sent with requests and must be accessed via JavaScript. Cookies support httpOnly (no JavaScript access) and expiration. localStorage is larger (5MB vs 4KB) but is vulnerable to XSS since JavaScript can always read it.
What does the httpOnly cookie attribute do?
httpOnly prevents JavaScript from accessing the cookie. This protects against XSS attacks where malicious scripts try to steal session cookies. Always use httpOnly for authentication cookies. JavaScript-accessible data should use separate, non-sensitive cookies.
What does the SameSite cookie attribute do?
SameSite controls when cookies are sent with cross-site requests. Strict only sends cookies for same-site requests, preventing CSRF. Lax allows cookies for top-level navigation but blocks them on cross-site form posts. None allows cross-site but requires Secure flag.