Skip to main content

setCookie

Set a browser cookie.

Syntax​

cy.setCookie(name, value)
cy.setCookie(name, value, options)

Usage​

Correct Usage

cy.setCookie('auth_key', '123key') // Set the 'auth_key' cookie to '123key'

Arguments​

name (String)

The name of the cookie to set.

value (String)

The value of the cookie to set.

options (Object)

Pass in an options object to change the default behavior of cy.setCookie().

OptionDefaultDescription
logtrueDisplays the command in the Command log
domainHostname of the current URLThe domain the cookie is visible to
expiry20 years into the futureWhen the cookie expires, specified in seconds since Unix Epoch.
hostOnlyfalseWhether the cookie is a host-only cookie, (i.e. the request's host must exactly match the domain of the cookie)
httpOnlyfalseWhether the cookie is an HTTP only cookie
path/The cookie path
securefalseWhether the cookie is a secure cookie
timeoutresponseTimeoutTime to wait for cy.setCookie() to resolve before timing out
sameSiteundefinedCookie's SameSite value. If set, should be one of lax, strict, or no_restriction. Pass undefined to use the browser's default. Note: no_restriction can only be used if the secure flag is set to true.

Yields ​

cy.setCookie() yields a cookie object with the following properties:

  • domain
  • expiry (if specified)
  • hostOnly (if specified)
  • httpOnly
  • name
  • path
  • sameSite (if specified)
  • secure
  • value

Examples​

Name Value​

cy.getCookies().should('be.empty')
cy.setCookie('session_id', '189jd09sufh33aaiidhf99d09')
cy.getCookie('session_id').should(
'have.property',
'value',
'189jd09sufh33aaiidhf99d09'
)

Rules​

Requirements ​

  • cy.setCookie() requires being chained off of cy.

Assertions ​

  • cy.setCookie() will only run assertions you have chained once, and will not retry.

Timeouts ​

  • cy.setCookie() should never time out.
caution

Because cy.setCookie() is asynchronous it is technically possible for there to be a timeout while talking to the internal Cypress automation APIs. But for practical purposes it should never happen.

Command Log​

cy.getCookies().should('be.empty')
cy.setCookie('fakeCookie1', '123ABC')
cy.getCookie('fakeCookie1').should('have.property', 'value', '123ABC')

The commands above will display in the Command Log as:

Command Log setcookie

When clicking on setCookie within the command log, the console outputs the following:

Console Log setcookie

History​

VersionChanges
12.7.0Support hostOnly option for a given domain.
5.0.0Removed experimentalGetCookiesSameSite and made sameSite property always available.
4.3.0Added sameSite property when the experimentalGetCookiesSameSite configuration value is true.
0.16.0cy.setCookie() command added

See also​