Amblem
Furkan Baytekin

HTTP Cookie Attributes

HTTP cookie attributes to build secure and efficient web applications

HTTP Cookie Attributes
49
3 minutes

HTTP cookies are small pieces of data sent by a server to a user’s web browser. They play a vital role in maintaining sessions, personalizing user experiences, and enabling secure communication between clients and servers. However, managing cookies effectively requires understanding their attributes. Below, we explore key HTTP cookie attributes, their purposes, and how they impact web applications.


1. Name and Value

At the core of every cookie is its name and value pair. The name is a unique identifier for the cookie, while the value holds the data associated with that name. For example:

http
Set-Cookie: session_id=abc123;

In this example, session_id is the name, and abc123 is the value.

Best Practices:


2. HttpOnly

The HttpOnly attribute ensures that the cookie is accessible only via HTTP(S) requests, preventing JavaScript from accessing it through document.cookie.

http
Set-Cookie: session_id=abc123; HttpOnly;

Why It Matters:


3. Secure

The Secure attribute ensures that the cookie is transmitted only over secure channels, such as HTTPS.

http
Set-Cookie: session_id=abc123; Secure;

Why It Matters:

Note: Always use the Secure attribute with HTTPS to maintain confidentiality.


4. SameSite

The SameSite attribute restricts how cookies are sent with cross-site requests. It has three possible values:

http
Set-Cookie: session_id=abc123; SameSite=Strict;

Why It Matters:


5. Domain

The Domain attribute specifies the host(s) to which the cookie should be sent. By default, cookies are only sent to the origin that set them.

http
Set-Cookie: session_id=abc123; Domain=example.com;

Why It Matters:


6. Expires / Max-Age

These attributes define the lifespan of a cookie:

http
Set-Cookie: session_id=abc123; Expires=Wed, 01 Feb 2025 12:00:00 GMT;

or

http
Set-Cookie: session_id=abc123; Max-Age=3600;

Why It Matters:


7. Path

The Path attribute limits the cookie to a specific path within a domain.

http
Set-Cookie: session_id=abc123; Path=/account;

Why It Matters:


8. Last-Accessed

Though not an official attribute in the HTTP cookie specification, some systems track the last time a cookie was accessed. This information can be useful for:

Considerations:


Conclusion

Understanding and properly configuring HTTP cookie attributes is crucial for creating secure and efficient web applications. Attributes like HttpOnly, Secure, and SameSite help protect against attacks, while Expires, Path, and Domain provide control over cookie scope and lifespan. By leveraging these attributes wisely, developers can enhance user experience and security simultaneously.

Suggested Blog Posts