What is a Cookie?
A cookie is a mechanism to store small bits of data on the client’s browser. It enables the server to
remember information about the user and their interaction with the website, creating a seamless and
personalized browsing experience.
Detailed Examples of Cookies
1. Session Cookies:
o Example: A session cookie might store a unique identifier (sessionId) to keep a user
logged in as they navigate through pages.
o Behavior: It disappears when the browser is closed, ensuring that sensitive sessions
don’t persist unnecessarily.
o Use Case: Online shopping carts that maintain your items until checkout.
2. Persistent Cookies:
o Example: A persistent cookie can store a user's theme preference (e.g., theme=dark).
o Behavior: It has an expiration date (Expires=Wed, 09 Jun 2025 10:18:14 GMT) and stays
on the device until that time.
o Use Case: "Remember Me" functionality for login.
3. Third-party Cookies:
o Example: A third-party analytics service might set a cookie like trackingId=xyz123.
o Behavior: These cookies are sent with requests to third-party domains (e.g., ad networks
or analytics platforms).
o Use Case: Tracking user behavior across multiple websites for personalized ads.
Cookie Syntax in HTTP Header
1. Set-Cookie Header (Server to Client): When a server creates a cookie, it sends the Set-Cookie
header in the HTTP response.
Set-Cookie: sessionId=abc123; Path=/; Domain=example.com; Expires=Wed, 09 Jun 2025
10:18:14 GMT; HttpOnly; Secure; SameSite=Strict
o Path=/: Specifies the URL path for which the cookie is valid. The default is the path of
the page that set the cookie.
o Domain=example.com: Specifies the domain for which the cookie is valid.
o Expires: Specifies when the cookie will expire. Without this, it is treated as a session
cookie.
o HttpOnly: Makes the cookie inaccessible to JavaScript, protecting it from XSS attacks.
o Secure: Ensures the cookie is sent only over HTTPS, safeguarding it during transmission.
o SameSite: Controls cross-site request behavior:
▪ Strict: Prevents sending cookies with cross-site requests.
▪ Lax: Allows cookies for certain cross-site GET requests.
▪ None: Allows unrestricted cross-site requests (must also use Secure).
2. Cookie Header (Client to Server): Once set, the browser includes the cookie in subsequent
requests to the server.
Cookie: sessionId=abc123; theme=dark
What are HTTP Headers?
HTTP headers facilitate the exchange of metadata between the client and server during HTTP
communication. They play a crucial role in customizing the behavior of requests and responses.
Categories of HTTP Headers
1. Request Headers:
o Sent by the client (browser) to provide details about the request or client.
o Examples:
▪ Authorization: Contains credentials for authentication (e.g., Bearer <token>).
▪ User-Agent: Describes the client making the request (e.g., Mozilla/5.0).
▪ Accept: Specifies acceptable response formats (e.g., application/json).
GET /api/data HTTP/1.1
Host: example.com
Authorization: Bearer abc123
Accept: application/json
2. Response Headers:
o Sent by the server to provide additional context about the response.
o Examples:
▪ Content-Type: Indicates the MIME type of the response (e.g., text/html,
application/json).
▪ Server: Provides information about the server software (e.g., Apache/2.4.41).
HTTP/1.1 200 OK
Content-Type: application/json
Server: Apache/2.4.41
3. Entity Headers:
o Provide metadata about the body content.
o Examples:
▪ Content-Length: Specifies the size of the body in bytes.
▪ Content-Encoding: Indicates the encoding applied to the body (e.g., gzip).
HTTP/1.1 200 OK
Content-Length: 348
Content-Encoding: gzip
4. General Headers:
o Used in both requests and responses to manage communication behaviors.
o Examples:
▪ Cache-Control: Controls caching mechanisms.
▪ Connection: Manages connection persistence (e.g., keep-alive).
GET / HTTP/1.1
Host: example.com
Connection: keep-alive
Cache-Control: no-cache
How They Work Together
1. Login Example with Cookies and Headers:
o Initial Login Request: The client sends a request with login credentials.
o POST /login HTTP/1.1
o Host: example.com
o Content-Type: application/json
o { "username": "user", "password": "pass" }
o Server Response: The server authenticates the user and sets a session cookie.
o HTTP/1.1 200 OK
o Set-Cookie: sessionId=abc123; HttpOnly; Secure
o Subsequent Requests: The client includes the cookie in its requests.
o GET /dashboard HTTP/1.1
o Host: example.com
o Cookie: sessionId=abc123
2. User Tracking Example:
o Third-party Cookie: A third-party ad network sets a tracking cookie.
o Set-Cookie: trackingId=xyz789; Domain=ads.example.com; Secure; SameSite=None
o Behavior: This cookie enables the ad network to track the user across different websites.
By using cookies and HTTP headers effectively, websites can provide secure, efficient, and personalized
experiences.
Persistent Cookie vs. Session Cookie
Cookies are small pieces of data stored on a user's browser, and their behavior varies based on their
type: persistent or session cookies.
1. Persistent Cookies
A persistent cookie is designed to remain on a user's device until it expires or is manually deleted.
Key Characteristics:
• Duration: Persistent cookies have an explicit expiration date and time defined in the Expires or
Max-Age attribute.
o Example: Expires=Wed, 09 Jun 2025 10:18:14 GMT.
• Purpose: Used to store long-term information like user preferences, login credentials (for
"Remember Me" features), or theme settings.
• Storage: Saved in the browser’s storage (not just memory) and remains even after the browser is
closed.
• Example Use Case:
o Saving a user's language preference (lang=en) across visits to a website.
Example Syntax:
Set-Cookie: userId=12345; Expires=Wed, 09 Jun 2025 10:18:14 GMT; Path=/; Secure; HttpOnly
2. Session Cookies
A session cookie is temporary and exists only for the duration of the browser session. Once the browser
is closed, the cookie is deleted.
Key Characteristics:
• Duration: No explicit expiration date. It is stored in memory and automatically deleted when the
browser session ends.
• Purpose: Used for temporary purposes, like keeping a user logged in during a session or
maintaining a shopping cart state.
• Storage: Stored in the browser’s memory.
• Example Use Case:
o Managing a logged-in user’s session on an e-commerce website.
Example Syntax:
Set-Cookie: sessionId=abc123; Path=/; Secure; HttpOnly
Comparison Table
Feature Persistent Cookie Session Cookie
Storage Location Browser storage (file system) Browser memory
Lifespan Until expiration or manual deletion Until the browser is closed
Expiration Attribute Requires Expires or Max-Age attribute No expiration attribute
Use Case "Remember Me" login, user preferences Session-based activities
Example Language settings, authentication tokens Shopping cart, temporary sessions
Practical Example
Persistent Cookie Example: "Remember Me" Feature
1. Scenario: A user logs in and checks the "Remember Me" option.
2. Server Response:
3. Set-Cookie: authToken=xyz123; Expires=Wed, 09 Jun 2025 10:18:14 GMT; Path=/; Secure;
HttpOnly
4. Result: The browser saves the authToken cookie and uses it to log the user in automatically in
future sessions.
Session Cookie Example: Shopping Cart
1. Scenario: A user adds items to their cart on an e-commerce website.
2. Server Response:
3. Set-Cookie: cartId=abc789; Path=/; Secure; HttpOnly
4. Result: The cart is maintained while the browser session is active. Once the browser is closed,
the cookie and the cart state are deleted.
Both cookies are essential for creating dynamic and personalized web experiences, with persistent
cookies focusing on long-term needs and session cookies handling temporary, session-specific tasks.