Skip to main content
Cypress App

getCookie

Get a browser cookie by its name.

Syntax​

cy.getCookie(name)
cy.getCookie(name, options)

Usage​

Correct Usage

cy.getCookie('auth_key') // Get cookie with name 'auth_key'

Incorrect Usage

cy.getCookie() // Errors, a cookie name is required
cy.getCookie({ domain: 'example.com' }) // Errors, name must be a string

Arguments​

name (String)

The name of the cookie to get. Required, and must be a string.

options (Object)

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

OptionDefaultDescription
domainHostname of the application under testRetrieves the cookie from the specified domain
logtrueDisplays the command in the Command log
timeoutdefaultCommandTimeoutTime to wait for cy.getCookie() to resolve before timing out

Yields ​

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

  • domain: (String)
  • expiry: (Number) (if specified)
  • hostOnly: (Boolean) (not always reported)
  • httpOnly: (Boolean)
  • name: (String)
  • path: (String)
  • sameSite: (String) (if specified)
  • secure: (Boolean)
  • value: (String)

cy.getCookie() is a query, and it is safe to chain further commands. It re-reads the cookie on each retry, and the assertions you chain with .should() drive those retries. If an assertion fails, because the cookie is null or because a property doesn't match yet, the query reads the cookie again and re-runs the assertion until it passes or the command times out.

With no assertion chained, cy.getCookie() yields whatever it reads on the first attempt. A .then() callback runs once and isn't retried, so chain .should('exist') before it to wait for a cookie that your application sets asynchronously.

cy.getCookie() yields null.

Examples​

Session id​

info

The Logging In recipes use cy.getCookie() to test logging in with HTML web forms, XHR web forms, and single sign-on.

In this example, your server sends back a session cookie on login.

// assume the user just logged in
cy.contains('Login').click()
cy.url().should('include', 'profile')
// retries until cookie with value=189jd09su
// is found or default command timeout ends
cy.getCookie('session_id').should('have.property', 'value', '189jd09su')

To check that the cookie exists without comparing any of its properties, assert exist:

cy.getCookie('my-session-cookie').should('exist')

Send the session cookie's value in a request header​

To pass the cookie's value to a later command, chain .its('value') and use the value inside .then(). Cypress runs the callback after .its() finds the value, so cy.request() gets the current value rather than one read when the test queued its commands.

cy.getCookie('session_id')
.its('value')
.then((token) => {
cy.request({
url: '/api/admin',
headers: {
'my-token-x': token,
},
})
})

Assert not.exist to confirm a cookie is gone. The query retries until the assertion passes, so it waits for a logout request that clears the cookie after a short delay.

cy.contains('Log out').click()
cy.getCookie('session_id').should('not.exist')

.its() yields a single property of the cookie. Because .its() is also a query, the assertion still retries cy.getCookie(), so the test waits for a cookie that hasn't been set yet.

cy.getCookie('csrf_token').its('value').should('have.length', 32)

Assert include with the attributes your server must set. The assertion passes when the cookie has every listed property with the listed value.

cy.getCookie('session_id').should('include', {
httpOnly: true,
secure: true,
sameSite: 'strict',
})

sameSite is 'lax', 'strict', or 'no_restriction' (the value for SameSite=None), or 'unspecified' in Firefox when the cookie doesn't set one.

expiry is the time the cookie expires, in seconds since the Unix epoch. This example checks that a cookie lasts at least 29 more days:

const twentyNineDays = 29 * 24 * 60 * 60

cy.getCookie('remember_me')
.its('expiry')
.should('be.greaterThan', Date.now() / 1000 + twentyNineDays)

A cookie set without an expiry date has no expiry property, so .its('expiry') fails for it.

By default, cy.getCookie() reads cookies for the hostname of the application under test. Pass domain to read a cookie set for a different domain, such as an API on a sibling domain: api.example.com when your app runs on app.example.com.

cy.getCookie('refresh_token', { domain: 'api.example.com' }).should('exist')

Validate a cy.session() login with cy.getCookie()​

Use cy.getCookie() in the validate function of cy.session() to confirm the login cookie is set. Cypress saves the session's cookies again after validate passes, so a cookie that arrives after the login click is still part of the cached session.

cy.session(
username,
() => {
cy.visit('/login')
cy.get('#username').type(username)
cy.get('#password').type(password)
cy.contains('Log in').click()
},
{
validate() {
cy.getCookie('session_id').should('exist')
},
}
)

To confirm that your server still accepts a restored session, see validating the session.

Notes​

The domain option defaults to the hostname of the application under test. Before cy.visit() loads a page, the application under test is on about:blank, so Cypress uses the hostname it serves the spec from instead (usually localhost). Pass domain explicitly to work with cookies on another domain before visiting.

Which cookies cy.getCookie() matches by domain​

cy.getCookie() looks for the cookie on the requested domain: the domain option if you pass one, otherwise the hostname of the application under test. It matches the same domain and any parent domain the cookie was set on, but not a subdomain or a sibling domain. When the application under test is on app.example.com, or you pass domain: 'app.example.com':

Cookie set onYielded by cy.getCookie()
app.example.com (same domain)Yes
example.com (parent domain)Yes
api.app.example.com (subdomain)No
api.example.com (sibling domain)No

Reading HttpOnly cookies with cy.getCookie()​

cy.getCookie() reads cookies through the browser, so it yields cookies marked HttpOnly, such as most session cookies. Your application's JavaScript can't see those through document.cookie, so reading document.cookie in a test misses them.

Why cy.getCookie() yields null​

If no cookie with the name is ever found, cy.getCookie('session_id').should('exist') fails with Timed out retrying after 4000ms: expected null to exist. Check these causes:

Rules​

Requirements ​

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

Assertions ​

  • cy.getCookie() automatically retries until all chained assertions have passed.

Timeouts ​

  • cy.getCookie() can time out waiting for assertions you've added to pass, or for the browser to return the cookie. Both waits use the defaultCommandTimeout, 4000 ms by default, or the timeout option, when passed.
  • If the application under test is on a different origin, cy.getCookie() retries until the command times out and then fails with a cross-origin error, even when you pass the domain option. Run it inside cy.origin() to read cookies on that origin, or use cy.getAllCookies(), which reads cookies on every domain without that check.
  • If the browser returns an error before the first read succeeds, cy.getCookie() fails right away instead of retrying.

Command Log​

Get a browser cookie and make assertions about the object

cy.getCookie('fakeCookie1').should('have.property', 'value', '123ABC')

The commands above display in the Command Log as:

Command Log showing getCookie for fakeCookie1, followed by a passing assertion that the cookie has a value property of 123ABC, displayed with stray asterisks around value and 123ABC

When you click getCookie in the Command Log, the console outputs the following. When no cookie matches, the console shows null as the yielded value, with a note that no cookie with that name was found.

Console output for getCookie showing Command: getCookie and, under Yielded, the fakeCookie1 cookie object with its name, value, path, secure, and httpOnly properties

History​

VersionChanges
16.0.0Now a query that retries assertions, with defaultCommandTimeout as its timeout. See the Migration Guide.
15.6.0In WebKit, prefers a cookie that matches the exact domain, falling back to a parent domain.
12.0.0The domain option defaults to the hostname instead of the superdomain.
11.0.0Added domain option.
5.0.0Removed experimentalGetCookiesSameSite and made sameSite property always available.
4.3.0Added sameSite property when the experimentalGetCookiesSameSite configuration value is true.

See also​