Set-Cookie Header
Table of Content
The Set-Cookie HTTP response header is used to send cookies from a server to a user's web browser. These cookies are small pieces of data that the server sends to the user's browser, which the browser may send back to the server when making subsequent requests. The purpose of this header is to enable session management, personalization, and tracking user behavior on websites.
Syntax
The syntax for the Set-Cookie HTTP response header is as follows:
Set-Cookie: <cookie-name>=<cookie-value>; <directive1>=<value1>; <directive2>=<value2>; ...
Directives
There are several directives that you can use with the Set-Cookie header:
Secure
- This directive indicates that the cookie should only be sent over HTTPS.HttpOnly
- This directive restricts the cookie from being accessed by JavaScript.Domain
- This directive specifies the domain within which the cookie is valid.Path
- This directive defines the path within the specified domain that the cookie is valid for.SameSite
- This directive controls whether the cookie is sent with cross-site requests.
Examples
Here is an example of how to use the Set-Cookie header:
Set-Cookie: sessionId=38fj392j392j; Domain=example.com; Path=/; Secure; HttpOnly
In this example, a secure, http-only cookie named sessionId
is being set, with a value of 38fj392j392j
. The cookie is valid for any path within example.com
.
Browser Compatibility
Browser | Compatibility |
---|---|
Chrome | Supported |
Firefox | Supported |
Safari | Supported |
Opera | Supported |
Edge | Supported |
How to modify Set-Cookie header
ModHeader is a Chrome extension that can modify HTTP request and response headers. To modify the Set-Cookie header, you would open the ModHeader extension, then add a new Set-Cookie response mod. Enter the cookie name and value, and specify the cookie attributes as needed. They will get serialized into a Set-Cookie
header string, e.g., sessionId=38fj392j392j; Domain=example.com; Path=/; Secure; HttpOnly
.
Modifying the Set-Cookie header can be useful for testing how your website behaves with different cookie values without having to actually change any server-side code. It can also be helpful for testing the impacts of changing cookie directives (e.g., marking a cookie as Secure
or HttpOnly
) on your website's functionality.