Cookies are small pieces of data that a web server sends to a user's browser.
The browser then stores these cookies and sends them back to the same server
with subsequent requests. This mechanism allows web applications to "remember"
information about the user, such as login status, preferences, or items in a
shopping cart, across multiple page views and even over time.
Invented by Lou Montulli in 1994 while working at Netscape, cookies
revolutionized how web applications could offer personalized experiences.
How Cookies Work
The process involves the following steps:
A user visits a website.
The web server sends an HTTP response to the browser, which includes a
Set-Cookie header. This header contains the cookie's name, value,
and other attributes.
The browser receives the cookie and stores it locally, associated with the
domain of the website that sent it.
On subsequent requests to the same domain, the browser automatically includes
any relevant cookies in the Cookie HTTP header of the request.
The web server can then read these cookies from the incoming request to identify
the user or retrieve their preferences.
Key Cookie Attributes
Cookies are defined by several attributes that control their behavior and scope.
Example: Basic Set-Cookie Header
HTTP/1.1 200 OK
Content-Type: text/html
Set-Cookie: userId=12345; Expires=Wed, 21 Oct 2025 07:28:00 GMT; Path=/; Domain=example.com; Secure; HttpOnly
Name-Value Pair
This is the core of a cookie, consisting of a name and its associated value.
For example, sessionID=abc123xyz.
Expires
Specifies the date and time at which the cookie should be deleted by the browser.
If omitted, the cookie is a "session cookie" and is deleted when the browser
is closed.
Format: Expires=Wdy, DD Mon YYYY HH:MM:SS GMT
Max-Age
Specifies the duration, in seconds, from the time the cookie is set until it
expires. This is a more modern and preferred alternative to Expires.
A value of 0 indicates the cookie should be deleted immediately.
Format: Max-Age=seconds
Domain
Specifies the domain for which the cookie is valid. If omitted, it defaults to the
domain of the server that set the cookie. A domain like .example.com
would make the cookie accessible to subdomains like www.example.com
and api.example.com.
Path
Specifies the URL path on the server for which the cookie is valid. If omitted,
it defaults to the path of the URL that generated the cookie. For example,
Path=/admin would mean the cookie is only sent for requests starting
with /admin.
Secure
If present, this attribute indicates that the cookie should only be transmitted
over encrypted HTTPS connections. It is a crucial security measure.
HttpOnly
If present, this attribute prevents JavaScript from accessing the cookie. This is
a vital defense against Cross-Site Scripting (XSS) attacks, as it makes it harder
for malicious scripts to steal sensitive cookie data, like session IDs.
SameSite
This attribute helps mitigate Cross-Site Request Forgery (CSRF) attacks by
controlling when cookies are sent with cross-site requests. Common values are:
Strict: The cookie is only sent for same-site requests.
Lax: The cookie is sent for same-site requests and for
top-level navigation GET requests initiated by a third-party.
None: The cookie is sent with all requests, but requires the
Secure attribute (i.e., only over HTTPS).
Setting Cookies (HTTP Headers)
Web servers set cookies using the Set-Cookie header in their HTTP
responses.
Server-side Example (Conceptual - e.g., Node.js/Express)
// Setting a persistent cookie
res.cookie('theme', 'dark', {
expires: new Date(Date.now() + 86400000), // 1 day
httpOnly: true,
secure: true,
sameSite: 'lax'
});
// Setting a session cookie
res.cookie('sessionID', 'abcdef123456', { httpOnly: true });
Reading Cookies (HTTP Headers)
Browsers send cookies back to the server using the Cookie header in
HTTP requests.
Incoming Request Header Example
GET /profile HTTP/1.1
Host: example.com
Cookie: theme=dark; sessionID=abcdef123456
Server-side code would then parse this header to extract the cookie values.
Working with Cookies in JavaScript
Client-side JavaScript can access and manipulate cookies through the
document.cookie property. However, this access is restricted by the
HttpOnly attribute.
JavaScript Example
// Get all cookies
let allCookies = document.cookie;
console.log(allCookies); // e.g., "theme=dark; sessionID=abcdef123456"
// Set a cookie
document.cookie = "username=johnDoe; expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/";
// Read a specific cookie (requires parsing)
function getCookie(name) {
const nameEQ = name + "=";
const ca = document.cookie.split(';');
for(let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
let username = getCookie("username");
console.log(username); // "johnDoe"
// Delete a cookie (by setting an expiration date in the past)
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Important: Cookies set with the HttpOnly flag cannot be
accessed or modified by client-side JavaScript, which is a crucial security feature.
Common Use Cases for Cookies
Session Management: Storing session IDs to keep users logged in.
Personalization: Remembering user preferences like language, theme, or layout.
Tracking: Recording user behavior for analytics or advertising purposes.
Shopping Carts: Storing items added to a cart before checkout.
User Identification: Remembering returning users.
Security Considerations
While essential, cookies pose security risks if not handled properly:
Session Hijacking: If session cookies are intercepted, an attacker could impersonate the user. Using the Secure and HttpOnly flags, along with robust session management on the server, is vital.
Cross-Site Scripting (XSS): Malicious scripts can steal cookies if HttpOnly is not used.
Cross-Site Request Forgery (CSRF): Attackers can trick users into performing unwanted actions. The SameSite attribute helps mitigate this.
Data Exposure: Storing sensitive information directly in cookies (like passwords or credit card numbers) is strongly discouraged. Cookies should primarily store tokens or identifiers.
Privacy and Regulations
The use of cookies, particularly for tracking and advertising, has raised significant privacy concerns. Regulations like the GDPR (General Data Protection Regulation) and CCPA (California Consumer Privacy Act) mandate that websites obtain user consent before setting non-essential cookies. Developers must be mindful of these regulations and provide clear information to users about cookie usage.
Websites should implement cookie consent banners and offer users control over which types of cookies they accept.