Set-Cookie header

The Set-Cookie HTTP header is used by web servers to send cookies to the user's browser. These cookies are then stored on the client-side and sent back to the server with subsequent requests. This mechanism is essential for maintaining stateful information across multiple HTTP requests, which is inherently stateless.

Structure of the Set-Cookie header

A typical Set-Cookie header looks like this:

Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date>; Max-Age=<seconds>; Path=<path>; Domain=<domain>; Secure; HttpOnly; SameSite=<samesite>; Partitioned; Priority=<priority>

Components

  • =: The name and value of the cookie.
  • Expires=: The expiration date of the cookie. If not set, the cookie is a session cookie and will be deleted when the browser is closed.
  • Max-Age=: Cookie should be retained for the specified number of seconds. Max-Age takes precedence over Expires.
  • Path=: The URL path that must exist in the requested URL for the browser to send the Cookie header.
  • Domain=: The domain that must exist in the requested URL for the browser to send the Cookie header.
  • Secure: Indicates that the cookie should only be sent over HTTPS.
  • HttpOnly: Indicates that the cookie is not accessible via JavaScript, helping to mitigate cross-site scripting (XSS) attacks.
  • SameSite=: Controls whether a cookie is sent with cross-site requests, providing some protection against cross-site request forgery (CSRF) attacks. Values can be Strict, Lax, or None.
  • Partitioned: Cookies marked Partitioned are double-keyed: by the origin that sets them and the origin of the top-level page.
  • Priority=: The attribute indicates a retention priority relative to other cookies from the same domain as the cookie carrying the attribute. During cookie eviction in enforcement of per-domain cookie limits, "Low" priority cookies will be evicted before "Medium" and "Medium" before "High". Cookies without a specified priority are considered to have "Medium" priority.

Purpose of the Set-Cookie Header

The primary purpose of the Set-Cookie header is to manage user sessions. For example, when a user logs into a website, the server can send a session cookie to the browser. This cookie will then be included in subsequent requests, allowing the server to recognize the user and maintain their session.

Cookies can also be used for:

  • Personalization: Storing user preferences and settings.
  • Tracking: Monitoring user behavior for analytics and advertising purposes.
  • Authentication: Keeping users logged in across multiple requests.

By understanding and properly utilizing the Set-Cookie header, developers can create more dynamic and user-friendly web applications.


Choose from 119 ops
Latest ops 0
Favorite ops 0
Calculations
0