Set-Cookie header
BaselineWidely available *
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
* Some parts of this feature may have varying levels of support.
The HTTPSet-Cookie
response header is used to send a cookie from the server to the user agent, so that the user agent can send it back to the server later.To send multiple cookies, multipleSet-Cookie
headers should be sent in the same response.
Warning:Browsers block frontend JavaScript code from accessing theSet-Cookie
header, as required by the Fetch spec, which definesSet-Cookie
as aforbidden response header name thatmust be filtered out from any response exposed to frontend code.
When aFetch API orXMLHttpRequest API requestuses CORS, browsers will ignoreSet-Cookie
headers present in the server's response unless the request includes credentials. VisitUsing the Fetch API - Including credentials and theXMLHttpRequest article to learn how to include credentials.
For more information, see the guide onUsing HTTP cookies.
Syntax
Set-Cookie: <cookie-name>=<cookie-value>Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date>Set-Cookie: <cookie-name>=<cookie-value>; HttpOnlySet-Cookie: <cookie-name>=<cookie-value>; Max-Age=<number>Set-Cookie: <cookie-name>=<cookie-value>; PartitionedSet-Cookie: <cookie-name>=<cookie-value>; Path=<path-value>Set-Cookie: <cookie-name>=<cookie-value>; SecureSet-Cookie: <cookie-name>=<cookie-value>; SameSite=StrictSet-Cookie: <cookie-name>=<cookie-value>; SameSite=LaxSet-Cookie: <cookie-name>=<cookie-value>; SameSite=None; Secure// Multiple attributes are also possible, for example:Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure; HttpOnly
Attributes
<cookie-name>=<cookie-value>
Defines the cookie name and its value.A cookie definition begins with a name-value pair.
A
<cookie-name>
can contain any US-ASCII characters except for: control characters (ASCII characters 0 up to 31 and ASCII character 127) or separator characters (space, tab and the characters:( ) < > @ , ; : \ " / [ ] ? = { }
)A
<cookie-value>
can optionally be wrapped in double quotes and include any US-ASCII character excluding control characters (ASCII characters 0 up to 31 and ASCII character 127),Whitespace, double quotes, commas, semicolons, and backslashes.Encoding: Many implementations performpercent-encoding on cookie values.However, this is not required by the RFC specification.The percent-encoding does help to satisfy the requirements of the characters allowed for
<cookie-value>
.Note:Some
<cookie-name>
have a specific semantic:__Secure-
prefix: Cookies with names starting with__Secure-
(dash is part of the prefix) must be set with thesecure
flag from a secure page (HTTPS).__Host-
prefix: Cookies with names starting with__Host-
are sent only to the host subdomain or domain that set them, and not to any other host.They must be set with thesecure
flag, must be from a secure page (HTTPS), must not have a domain specified, and the path must be/
.Domain=<domain-value>
OptionalDefines the host to which the cookie will be sent.
Only the current domain can be set as the value, or a domain of a higher order, unless it is a public suffix. Setting the domain will make the cookie available to it, as well as to all its subdomains.
If omitted, this attribute defaults to the host of the current document URL, not including subdomains.
Contrary to earlier specifications, leading dots in domain names (
.example.com
) are ignored.Multiple host/domain values arenot allowed, but if a domainis specified, then subdomains are always included.
Expires=<date>
OptionalIndicates the maximum lifetime of the cookie as an HTTP-date timestamp.See
Date
for the required formatting.If unspecified, the cookie becomes asession cookie.A session finishes when the client shuts down, after whichthe session cookie is removed.
Warning:Many web browsers have asession restore feature that will save all tabs and restore them the next time the browser is used. Session cookies will also be restored, as if the browser was never closed.
The
Expires
attribute is set by the server with a value relative to its own internal clock, which may differ from that of the client browser.Firefox and Chromium-based browsers internally use an expiry (max-age) value that is adjusted to compensate for clock difference, storing and expiring cookies based on the time intended by the server.The adjustment for clock skew is calculated from the value of theDATE
header.Note that the specification explains how the attribute should be parsed, but does not indicate if/how the value should be corrected by the recipient.HttpOnly
OptionalForbids JavaScript from accessing the cookie, for example, through the
Document.cookie
property.Note that a cookie that has been created withHttpOnly
will still be sent with JavaScript-initiated requests, for example, when callingXMLHttpRequest.send()
orfetch()
.This mitigates attacks against cross-site scripting (XSS).Max-Age=<number>
OptionalIndicates the number of seconds until the cookie expires. A zero or negative number will expire the cookie immediately. If both
Expires
andMax-Age
are set,Max-Age
has precedence.Partitioned
OptionalIndicates that the cookie should be stored using partitioned storage.Note that if this is set, the
Secure
directive must also be set.SeeCookies Having Independent Partitioned State (CHIPS) for more details.Path=<path-value>
OptionalIndicates the path thatmust exist in the requested URL for the browser to send the
Cookie
header.The forward slash (
/
) character is interpreted as a directory separator, and subdirectories are matched as well. For example, forPath=/docs
,- the request paths
/docs
,/docs/
,/docs/Web/
, and/docs/Web/HTTP
will all match. - the request paths
/
,/docsets
,/fr/docs
will not match.
Note:The
path
attribute lets you control what cookies the browser sends based on the different parts of a site.It is not intended as a security measure, anddoes not protect against unauthorized reading of the cookie from a different path.- the request paths
SameSite=<samesite-value>
OptionalControls whether or not a cookie is sent with cross-site requests: that is, requests originating from a differentsite, including the scheme, from the site that set the cookie. This provides some protection against certain cross-site attacks, includingcross-site request forgery (CSRF) attacks.
The possible attribute values are:
Strict
Send the cookie only for requests originating from the samesite that set the cookie.
Lax
Send the cookie only for requests originating from the samesite that set the cookie, and for cross-site requests that meet both of the following criteria:
The request is a top-level navigation: this essentially means that the request causes the URL shown in the browser's address bar to change.
This would exclude, for example, requests made using the
fetch()
API, or requests for subresources from<img>
or<script>
elements, or navigations inside<iframe>
elements.It would include requests made when the user clicks a link in the top-level browsing context from one site to another, or an assignment to
document.location
, or a<form>
submission.
The request uses asafe method: in particular, this excludes
POST
,PUT
, andDELETE
.
Some browsers use
Lax
as the default value ifSameSite
is not specified: seeBrowser compatibility for details.Note:When
Lax
is applied as a default, a more permissive version is used. In this more permissive version, cookies are also included inPOST
requests, as long as they were set no more than two minutes before the request was made.None
Send the cookie with both cross-site and same-site requests.The
Secure
attribute must also be set when using this value.
Secure
OptionalIndicates that the cookie is sent to the server only when a request is made with the
https:
scheme (except on localhost), and therefore, is more resistant toman-in-the-middle attacks.Note:Do not assume that
Secure
prevents all access to sensitive information in cookies (session keys, login details, etc.).Cookies with this attribute can still be read/modified either with access to the client's hard disk or from JavaScript if theHttpOnly
cookie attribute is not set.Insecure sites (
http:
) cannot set cookies with theSecure
attribute. Thehttps:
requirements are ignored when theSecure
attribute is set by localhost.
Examples
Session cookie
Session cookies are removed when the client shuts down. Cookies are session cookies if they do not specify theExpires
orMax-Age
attribute.
Set-Cookie: sessionId=38afes7a8
Permanent cookie
Permanent cookies are removed at a specific date (Expires
) or after a specific length of time (Max-Age
) and not when the client is closed.
Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT
Set-Cookie: id=a3fWa; Max-Age=2592000
Invalid domains
A cookie for a domain that does not include the server that set itshould be rejected by the user agent.
The following cookie will be rejected if set by a server hosted onoriginal-company.com
:
Set-Cookie: qwerty=219ffwef9w0f; Domain=some-company.co.uk
A cookie for a subdomain of the serving domain will be rejected.
The following cookie will be rejected if set by a server hosted onexample.com
:
Set-Cookie: sessionId=e8bb43229de9; Domain=foo.example.com
Cookie prefixes
Cookie names prefixed with__Secure-
or__Host-
can be used only if they are set with thesecure
attribute from a secure (HTTPS) origin.
In addition, cookies with the__Host-
prefix must have a path of/
(meaning any path at the host) and must not have aDomain
attribute.
Warning:For clients that don't implement cookie prefixes, you cannot count on these additional assurances, and prefixed cookies will always be accepted.
// Both accepted when from a secure origin (HTTPS)Set-Cookie: __Secure-ID=123; Secure; Domain=example.comSet-Cookie: __Host-ID=123; Secure; Path=/// Rejected due to missing Secure attributeSet-Cookie: __Secure-id=1// Rejected due to the missing Path=/ attributeSet-Cookie: __Host-id=1; Secure// Rejected due to setting a DomainSet-Cookie: __Host-id=1; Secure; Path=/; Domain=example.com
Partitioned cookie
Set-Cookie: __Host-example=34d8g; SameSite=None; Secure; Path=/; Partitioned;
Note:Partitioned cookies must be set withSecure
. In addition, it is recommended to use the__Host
prefix when setting partitioned cookies to make them bound to the hostname and not the registrable domain.
Specifications
Specification |
---|
HTTP State Management Mechanism # sane-set-cookie |
Browser compatibility
See also
- HTTP cookies
Cookie
Document.cookie
- Samesite cookies explained (web.dev blog)