Cookie
A cookie is a small piece of data stored by a web browser to remember user information, preferences, or session state.
What is a cookie?
A cookie is a small text file created by a website and stored in the user's web browser. Cookies allow websites to remember stateful information across requests, such as login status, user preferences, or tracking identifiers.
Cookies are sent back to the server with subsequent HTTP requests to the same domain.
Why cookies matter
Cookies are essential because they:
- Enable user authentication and sessions
- Preserve preferences and settings
- Support shopping carts and forms
- Allow analytics and performance measurement
- Power personalization and targeted content
Without cookies, most modern web applications would not function correctly.
How cookies work (simplified)
- Server sends a
Set-Cookieheader to the browser - Browser stores the cookie locally
- Browser sends the cookie back with future requests
- Server uses the cookie to identify or remember the client
Cookies bridge the stateless nature of HTTP.
Common types of cookies
Cookies are commonly classified as:
- Session cookies -- temporary, deleted when the browser closes
- Persistent cookies -- stored for a defined duration
- First-party cookies -- set by the visited website
- Third-party cookies -- set by external domains
- Secure cookies -- sent only over HTTPS
- HttpOnly cookies -- inaccessible to client-side scripts
Each type serves a specific purpose.
Cookies and authentication
In web applications, cookies often:
- Store session identifiers
- Maintain login state
- Associate users with server-side sessions
They must be protected to prevent session hijacking.
Cookies and privacy
From a privacy perspective:
- Cookies can track user behavior across sessions
- Third-party cookies enable cross-site tracking
- Regulations require transparency and consent
- Users can view, block, or delete cookies
Privacy controls have become a major design consideration.
Security considerations
Cookies can be abused if not properly secured:
- Session hijacking via stolen cookies
- Cross-site scripting (XSS) access to cookies
- Cross-site request forgery (CSRF) risks
- Insecure transmission over HTTP
Security flags significantly reduce these risks.
Cookie attributes (key examples)
Common cookie attributes include:
Expires/Max-Age-- lifetimeSecure-- HTTPS-only transmissionHttpOnly-- inaccessible to JavaScriptSameSite-- controls cross-site sendingDomain/Path-- scope of validity
Correct configuration is critical.
Cookies vs local storage
| Feature | Cookies | Local Storage |
|---|---|---|
| Sent with requests | Yes | No |
| Size limit | Small | Larger |
| Expiration | Yes | Manual |
| Security flags | Yes | Limited |
Cookies are better suited for server-managed sessions.
Common misconceptions
- "Cookies are always malicious"
- "Cookies store passwords"
- "Deleting cookies breaks the internet"
- "Cookies are only used for ads"