Cookie Storage
What It Is
A cookie is a small piece of data stored by the browser and sent back to the server with later HTTP requests.
Cookies help web applications remember state because HTTP is stateless by default.
Cookie = Small key-value data stored in browser and sent with HTTP requests
Why It Matters
Cookies are useful when the server needs to remember something about the user or session across requests.
Unlike sessionStorage, cookies can persist across browser sessions.
Unlike localStorage, cookies can be automatically sent with HTTP requests.
Common uses:
- session management
- authentication session identifiers
- user preferences
- language settings
- theme settings
Browser stores cookie -> Browser sends cookie with later requests -> Server remembers state
How Cookies Work
Cookies can be created by the server or by JavaScript.
The server usually sends cookies using the Set-Cookie HTTP header.
Set-Cookie: sessionId=abc123
After storing the cookie, the browser may send it back to the same server on future requests.
Cookie: sessionId=abc123
Cookies can also be created, updated, and read using JavaScript with document.cookie.
Basic JavaScript Usage
Cookies are stored as key-value pairs.
Set Cookie
document.cookie = "yummy_cookie=choco";
document.cookie = "tasty_cookie=strawberry";
Read Cookies
console.log(document.cookie);
Output:
yummy_cookie=choco; tasty_cookie=strawberry
Update Cookie
Setting a cookie with the same name updates its value.
document.cookie = "yummy_cookie=blueberry";
console.log(document.cookie);
Output:
tasty_cookie=strawberry; yummy_cookie=blueberry
Cookie Attributes
Cookie attributes control where, when, and how cookies are used.
| Attribute | Purpose |
|---|---|
| domain | Defines which domain can receive the cookie |
| expires | Sets cookie expiry using a date |
| max-age | Sets cookie lifetime in seconds |
| SameSite | Controls when cookie is sent in cross-site requests |
| Secure | Sends cookie only over HTTPS |
| HttpOnly | Prevents JavaScript access to the cookie |
| Path | Restricts cookie to a specific path |
Attributes are added after the key-value pair using semicolons.
document.cookie = "theme=dark; max-age=31536000; path=/";
Expiry and Max-Age
Cookies can be temporary or persistent.
If no expires or max-age is set, the cookie usually expires when the session ends.
Expires
document.cookie = "language=en; expires=Fri, 31 Dec 2027 23:59:59 GMT; path=/";
Max-Age
document.cookie = "language=en; max-age=31536000; path=/";
max-age defines how long the cookie should live in seconds.
SameSite
The SameSite attribute controls when cookies are sent with cross-site requests.
| Value | Meaning |
|---|---|
| Lax | Sent for same-site requests and top-level navigation GET requests |
| Strict | Not sent in cross-site browsing contexts |
| None | Sent in both same-site and cross-site requests |
Modern browsers commonly use Lax as the default.
SameSite helps reduce Cross-Site Request Forgery risk.
Set-Cookie: sessionId=abc123; SameSite=Lax
Secure
The Secure attribute ensures cookies are sent only over secure protocols like HTTPS.
Set-Cookie: sessionId=abc123; Secure
Use Secure for cookies that should not travel over unencrypted HTTP connections.
HttpOnly
The HttpOnly attribute prevents JavaScript from accessing the cookie using document.cookie.
Set-Cookie: sessionId=abc123; HttpOnly
This improves security because client-side scripts cannot read the cookie.
It helps reduce risk if an XSS issue exists.
HttpOnly cookie -> browser sends it to server -> JavaScript cannot read it
Domain and Path
Domain controls which host can receive the cookie.
Path controls which URL path can receive the cookie.
Set-Cookie: userPref=dark; Domain=example.com; Path=/dashboard
These attributes help restrict where the cookie is available.
Use them carefully to avoid exposing cookies to unnecessary parts of the application.
Cookie Persistence
Cookies can be session-based or persistent.
| Type | Behavior |
|---|---|
| Session Cookie | Expires when the session ends |
| Persistent Cookie | Expires based on expires or max-age |
No expiry set -> session cookie
Expiry set -> persistent cookie
Cookie persistence should match the purpose of the data.
Do not keep cookies longer than necessary.
Data Structure
Cookies store simple key-value data.
They can also include attributes such as:
- expiry
- max age
- path
- domain
- secure flag
- HttpOnly flag
- SameSite value
Example:
Set-Cookie: theme=dark; Max-Age=31536000; Path=/; SameSite=Lax; Secure
Cookies are not suitable for complex or large data structures.
Size and Performance
Cookies have a small storage limit.
Each cookie can store around 4KB of data.
Performance matters because cookies are sent with HTTP requests.
Large or too many cookies can cause:
- increased request size
- extra bandwidth usage
- higher latency
- slower network communication
More cookie data -> larger HTTP requests
Keep cookies small and purposeful.
Security
Cookies can be more secure than JavaScript storage when configured correctly, but they must be handled carefully.
Important security practices:
- use
HttpOnlyto block JavaScript access - use
Secureto send cookies only over HTTPS - use
SameSiteto reduce CSRF risk - set proper
ExpiresorMax-Age - restrict cookie scope using
DomainandPath - avoid storing passwords, payment details, or personal data
- do not keep cookies longer than needed
Secure cookie setup = HttpOnly + Secure + SameSite + proper expiry
When to Use
Use cookies when data needs to be sent with HTTP requests or used for session-related behavior.
Good use cases:
- session management
- authenticated session identifiers
- server-readable preferences
- language preference
- theme preference
Example:
Set-Cookie: sessionId=abc123; HttpOnly; Secure; SameSite=Lax
Cookies are useful when the server needs the value on future requests.
When Not to Use
Avoid cookies when the data is sensitive, large, or does not need to be sent with every HTTP request.
Do not use cookies for:
- passwords
- payment information
- large data storage
- unnecessary client-only state
- data that should not be sent to the server
- personal data without proper protection
If the server does not need it, avoid sending it in cookies.
Cookies vs localStorage vs sessionStorage
| Feature | Cookies | localStorage | sessionStorage |
|---|---|---|---|
| Sent with requests | Yes | No | No |
| Persistence | Session or persistent | Persistent | Tab session |
| Size | Around 4KB per cookie | Around 5MB per domain | Around 5MB per origin |
| Access from JS | Yes, unless HttpOnly | Yes | Yes |
| Best for | Session and server-readable data | Small persistent client data | Temporary tab data |
| Security control | HttpOnly, Secure, SameSite | JavaScript accessible | JavaScript accessible |
Cookie Storage Table
| Feature | Cookie Storage |
|---|---|
| Purpose | Store small state data for browser and server |
| Format | Key-value pairs with optional attributes |
| Persistence | Session-based or persistent |
| Size limit | Around 4KB per cookie |
| Request behavior | Sent with HTTP requests |
| JavaScript access | Available unless HttpOnly is set |
| Security attributes | HttpOnly, Secure, SameSite, Domain, Path |
| Best for | Session management and server-readable preferences |
| Avoid for | Large data, passwords, personal data, payment data |
Basic Checklist
Use cookies only for small data
Use cookies when server needs the value
Set proper expiry or max-age
Use HttpOnly for session cookies
Use Secure for HTTPS-only transmission
Use SameSite to reduce CSRF risk
Use Domain and Path to limit scope
Avoid storing sensitive raw data
Avoid storing large data
Do not overuse cookies because they are sent with requests
Interview Style Answer
Cookies are small key-value data stored by the browser and sent back to the server with later HTTP requests. They are useful because HTTP is stateless, so cookies help applications remember session or preference information. Cookies can be set by the server using the Set-Cookie header or manipulated using JavaScript through document.cookie. They can be session cookies or persistent cookies depending on expires or max-age. Cookies are limited to around 4KB each and are sent with HTTP requests, so large or excessive cookies can hurt performance. For security, cookies should use attributes like HttpOnly, Secure, SameSite, Domain, and Path, and should not store passwords, payment information, or sensitive personal data.
One-Line Summary
Cookie Storage = Small browser key-value storage that can persist and automatically travel with HTTP requests.
Final Mental Model
Need server to receive data automatically? -> Cookie
Need JavaScript-only persistent data? -> localStorage
Need tab-only temporary data? -> sessionStorage
Need secure session cookie? -> HttpOnly + Secure + SameSite
Need large data? -> Do not use cookies