Cookies are essential in web development, serving crucial roles in personalization and security. This blog explores the basics of cookies, their security considerations, and the regulations developers need to follow.
Cookies are small amounts of data, stored as strings, that a server sends to a browser. The browser stores, creates, or updates this data and sends it back to the same server for future use.
What are cookies for?
Cookies enable a server to verify if requests come from the same browser or user. This is achieved by the browser sending back the cookie issued by the server for identification purposes.
Use Cases
- Session management: User sign-in status, shopping cart contents, game scores, or any other user session-related details that the server needs to remember.
- Personalization: User preferences such as display language and UI theme.
- Tracking: Recording and analyzing user behavior. MDN
Note:
In the early days of the web, cookies were used for general data storage because there were no other options. Today, modern storage APIs like localStorage, sessionStorage, and indexedDB are preferred. Unlike cookies, these APIs are designed specifically for storage, support larger amounts of data, and do not send data with every request, which improves performance. Cookies, on the other hand, are limited to 4KB of storage and are sent with every request, potentially leading to poor performance.
Creating, Removing, Reading, and Updating Cookies
Create:
When a request is sent to a server, it can include one or more Set-Cookie
headers in its response. Each cookie consists of a name-value pair:
Set-Cookie: <cookie-name>=<cookie-value>
Example of an HTTP response:
HTTP/2.0 200 OK Content-Type: text/html Set-Cookie: yummy_cookie=chocolate Set-Cookie: tasty_cookie=strawberry [page content]
Example of the header for a new request from the same browser to the server:
GET /sample_page.html HTTP/2.0 Host: www.example.org Cookie: yummy_cookie=chocolate; tasty_cookie=strawberry
Remove:
Session Cookies
A session cookie lasts only for the duration of the "session" and is removed when the session ends --- typically when the browser is closed. This is the default behavior if no attributes are set.
Permanent Cookies
Developers can control the lifetime of a permanent cookie by setting an expiration date or a duration period.
Example with the Expires
Attribute:
Set-Cookie: id=a3fWa; Expires=Thu, 31 Oct 2021 07:28:00 GMT;
Example with the Max-Age
Attribute:
Set-Cookie: id=a3fWa; Max-Age=2592000
Note:
Expires
data must be set in the GMT timezone format.
When both attributes are provided, Max-Age
takes precedence and is less error-prone. If Max-Age
is set to zero or a negative value, the cookie is deleted.
Read via JavaScript:
We can read cookies stored in the browser using JavaScript.
document.cookie // cookie1=value1; cookie2=value2;...
This returns a single string containing all cookies, delimited by ;
. To retrieve a specific cookie value, we need to write additional code to parse the string.
Update:
To update a cookie value via HTTP, the server sends a Set-Cookie
header with the same cookie name and a new value.
Set-Cookie: id=new-value
Update via JavaScript:
We can create new cookies using JavaScript.
document.cookie = "yummy_cookie=chocolate"; document.cookie = "tasty_cookie=strawberry";
We can also update existing cookie values.
console.log(document.cookie); // logs "yummy_cookie=chocolate; tasty_cookie=strawberry" document.cookie = "yummy_cookie=blueberry"; console.log(document.cookie); // logs "tasty_cookie=strawberry; yummy_cookie=blueberry"
Notes:
Updating cookies is only possible if the HttpOnly
attribute is not set (as explained later in this blog) for security reasons.
When updating, only the value specified for the given cookie name is modified. Other cookies remain unchanged, and the cookie is not overwritten.
Security
Cookies can be visible to and modified by an end user, which can lead to security vulnerabilities. To mitigate this, specific attributes can be set on cookies.
Example:
Set-Cookie: id=a3fWa; Expires=Thu, 21 Oct 2021 07:28:00 GMT; Secure; HttpOnly
HttpOnly Attribute
A cookie with the HttpOnly
attribute prevents JavaScript from accessing it, such as through document.cookie
. This type of cookie is only accessible by the server, helping to mitigate risks like cross-site scripting attacks.
Secure Attribute
A cookie with the Secure
attribute is sent to the server only over an encrypted connection using the HTTPS protocol. It is not transmitted over the HTTP protocol (except for localhost during development).
Domain Attribute
When the Domain
attribute is specified, cookies can be accessed by the specified domain and its subdomains.
Example:
Set-Cookie: id=123, Domain=example.com
With the example above, the cookie is accessible from the domain example.com
and its subdomains, such as foo.example.com
.
While this makes the cookie more flexible, it can also reduce security.
By default (when the Domain attribute is not specified), cookies are only accessible from the domain that set them. This default behavior is safer because it limits access to the original server and excludes subdomains.
Path Attribute
The Path
attribute specifies the URL path that must be present in the requested URL for the browser to send the cookie in the Cookie header.
Example:
Set-Cookie: id=123, Path=/docs
The cookie will be sent with requests to URLs like:
/docs
/docs/
docs/Web
docs/Web/HTTP
However, it will not be sent with requests to URLs like:
/
/docsets
/fr/doc
Note that the path attribute is not a security feature.
SameSite Attribute
The SameSite
attribute is designed to control whether cookies are sent with cross-site requests. A cross-site request occurs when the site a user is visiting differs in domain and/or scheme (e.g., http, https) from the origin of the cookie. Examples include navigating to a page from another site or requests from embedded third-party content.
The SameSite
attribute helps mitigate risks like CSRF (cross-site request forgery) attacks and enhances user privacy.
SameSite=Strict
Cookies are only sent with requests to the origin site.
This is the most secure option and is suitable for sensitive data like authentication cookies.
SameSite=Lax
Cookies are sent with requests to the origin site, even when navigating from a different site.
This is useful for cases like partner affiliate links, where cookies are needed to track navigation for benefits or rewards.
SameSite=None
Cookies are sent with both cross-site and origin site requests.
This is useful for third-party services like ad-tech or analytics.
It must be used with the Secure attribute.
Third-Party Cookies and SameSite Attribute
The SameSite
attributes can help control the behavior of third-party cookies and protect user privacy. While third-party cookies are useful for legitimate purposes, such as sharing user profile information, tracking ad impressions, or collecting analytics across domains, they can also be misused. For example, they can create intrusive or malicious user experiences by tracking browsing history and preferences.
Cookie-Related Regulations
Developers must understand and adhere to regulations regarding cookies, such as:
- The General Data Privacy Regulation (GDPR) in the European Union
- The ePrivacy Directive in the EU
- The California Consumer Privacy Act
Top comments (1)
I have always been seeing cookies on websites but never knew what they were or what they do until now.