What are Cookies and How to Work with Them
Cookie is small data fragment (text) that browser saves on behalf of server or client.
They're designed for storing session state, authentication, user settings and analytics.
Cookie Example
Set-Cookie: userId=12345; Path=/; Expires=Wed, 09 Apr 2025 10:00:00 GMT;
This header tells browser: "Save cookie userId with value 12345, available across entire site (Path=/) and valid until specified date".
Where Cookies Are Used
- Authorization and session token storage
- User tracking (e.g., Google Analytics)
- User settings storage (language, theme)
- A/B testing and personalization
Cookie Settings
| Parameter | Description |
|---|---|
name=value | Cookie name and value |
Path | Limits path for which cookie is available |
Domain | Limits domain (or subdomain) |
Expires | Specifies date when cookie will be deleted |
Max-Age | Cookie lifetime in seconds |
Secure | Cookie will be transmitted only over HTTPS |
HttpOnly | Not accessible via document.cookie — protects from XSS |
SameSite | Controls behavior on cross-domain requests (Lax, Strict, None) |
Security
Important:
Use Secure and HttpOnly flags for all cookies containing sensitive data, especially authorization tokens!
Reading and Deleting Cookies in JavaScript
Read
console.log(document.cookie); // "name=value; theme=dark"
Delete
To delete cookie, set expires to past:
document.cookie = "theme=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Cookie Limitations
- Maximum ~20 cookies per domain
- Maximum size of one cookie — ~4KB
- Sent in every HTTP request → can increase traffic
- Not suitable for storing large data volumes
Conclusion:
Cookie is important browser data storage mechanism, especially for sessions and security. Use them thoughtfully, following privacy and secure transmission recommendations.