---
title: Custom Commands and Logging In Once with cy.session
description: Sooner or later every suite repeats the same steps in many tests, and
  the most expensive repeated step is logging in. This chapter turns repeated steps
  into…
source_url:
  html: https://testingbot.com/resources/courses/cypress/custom-commands-and-sessions
  md: https://testingbot.com/resources/courses/cypress/custom-commands-and-sessions.md
---

Course

[Cypress Tutorial: First Spec to CI](https://testingbot.com/resources/courses/cypress)

Chapter 6 of 11

1. [1 Cypress Tutorial for Beginners](https://testingbot.com/resources/courses/cypress)
2. [2 Install Cypress and Run a First Spec](https://testingbot.com/resources/courses/cypress/install-and-first-spec)
3. [3 Selectors and the Cypress Command Queue](https://testingbot.com/resources/courses/cypress/selectors-and-the-command-queue)
4. [4 Cypress Assertions and Waiting Without Sleeps](https://testingbot.com/resources/courses/cypress/assertions-and-waiting)
5. [5 Fixtures and Network Stubbing with cy.intercept](https://testingbot.com/resources/courses/cypress/fixtures-and-network-stubbing)
6. [6 Custom Commands and Logging In Once with cy.session](https://testingbot.com/resources/courses/cypress/custom-commands-and-sessions)
7. [7 Cypress Configuration, Environment Variables and Retries](https://testingbot.com/resources/courses/cypress/config-and-environment-variables)
8. [8 Cypress Component Testing vs End-to-End Testing](https://testingbot.com/resources/courses/cypress/component-testing)
9. [9 Run Cypress on TestingBot and in CI](https://testingbot.com/resources/courses/cypress/run-cypress-on-testingbot)
10. [10 Debugging Cypress Tests](https://testingbot.com/resources/courses/cypress/debugging-cypress-tests)
11. [11 Knowledge check](https://testingbot.com/resources/courses/cypress/knowledge-check)

[Exit course](https://testingbot.com/resources/courses)

 Chapter 6 of 11 Beginner 6 min read 3 quick checks Updated Nov 2026 

# Custom Commands and Logging In Once with cy.session
[Watch this chapter Starts at 3:40 in the 9:03 course video.](https://www.youtube.com/watch?v=Ty406iWkgN4&t=220s)On this page
1. [A first custom command](https://testingbot.com#a-first-custom-command)
2. [Why logging in needs special treatment](https://testingbot.com#why-logging-in-needs-special-treatment)
3. [A cy.login command built on cy.session](https://testingbot.com#a-cy-login-command-built-on-cy-session)
4. [Faster still: log in without the form](https://testingbot.com#faster-still-log-in-without-the-form)

Sooner or later every suite repeats the same steps in many tests, and the most expensive repeated step is logging in. This chapter turns repeated steps into custom commands, then makes login fast with `cy.session()`, which caches a logged-in browser state and restores it for each test.

## A first custom command[#](https://testingbot.com#a-first-custom-command)

Custom commands live in `cypress/support/commands.js`, which `cypress/support/e2e.js` imports before every spec. Add one:

```javascript
Cypress.Commands.add('addTodo', (text) => {
  cy.get('[data-test=new-todo]').type(`${text}{enter}`)
})
```

and use it like a built-in command:

```javascript
describe('custom commands', () => {
  beforeEach(() => {
    cy.visit('/todo')
  })

  it('adds two todos with cy.addTodo', () => {
    cy.addTodo('Buy milk')
    cy.addTodo('Pay rent')

    cy.get('.todo-list li').should('have.length', 4)
  })
})
```

The commands inside are queued like any others, so a custom command needs no `return` and no `await`.

When should something be a custom command? A good test is whether the name describes a user intention ("add a todo", "log in as admin") rather than a mechanical step. Commands that wrap a single `cy.get` with a different name add indirection without adding meaning. For grouping many steps about one page, plain JavaScript functions or modules work just as well; Cypress does not require page objects, and our [page object model course](https://testingbot.com/resources/courses/page-object-model) covers when they help.

You add `Cypress.Commands.add('addTodo', ...)` to a new file `cypress/support/todo-commands.js`. Every spec now fails with "cy.addTodo is not a function". What is missing?

 Custom commands must be registered in `cypress.config.js` Nothing imports the new file; add `import './todo-commands'` to `cypress/support/e2e.js` Command names cannot contain capital letters

Only the support file runs automatically before each spec. Any other file has to be imported from it, the same way the scaffolded `e2e.js` imports `commands.js`.

## Why logging in needs special treatment[#](https://testingbot.com#why-logging-in-needs-special-treatment)

Test isolation (chapter 1) clears cookies, `localStorage` and `sessionStorage` before every test. That is what keeps tests independent, but it also logs you out before every test. Logging in through the form each time works, and is slow: a suite with 200 tests fills in the login form 200 times.

`cy.session(id, setup, options)` solves this:

- The first time it runs with a given `id`, it clears the browser, runs your `setup` function, and saves the resulting cookies, `localStorage` and `sessionStorage`.
- Every later time in the same spec, it skips `setup` and restores the saved state.
- If you pass a `validate` function, it runs after every create and restore; if validation fails, the session is rebuilt from scratch.

## A cy.login command built on cy.session[#](https://testingbot.com#a-cy-login-command-built-on-cy-session)

The login form at `the-internet.herokuapp.com/login` accepts `tomsmith` / `SuperSecretPassword!` and sets a `rack.session` cookie. Add this to `cypress/support/commands.js`:

```javascript
Cypress.Commands.add('login', (username, password) => {
  cy.session(
    username,
    () => {
      cy.visit('https://the-internet.herokuapp.com/login')
      cy.get('#username').type(username)
      cy.get('#password').type(password, { log: false })
      cy.get('button[type=submit]').click()
      cy.contains('#flash', 'You logged into a secure area!')
    },
    {
      validate() {
        cy.getCookie('rack.session').should('exist')
      },
    },
  )
})
```

Things to notice:

- The **id** is the username, so logging in as two different users keeps two separate cached sessions.
- The setup function ends with an **assertion that the login worked**. Without it, `cy.session` would happily cache whatever state existed right after the click, possibly before the cookie was set.
- `{ log: false }` keeps the password out of the command log, screenshots and videos.
- `validate` checks the cookie is still there. A real application might instead call an endpoint that returns the current user with `cy.request` and check the status.

Then use it in `cypress/e2e/secure.cy.js`:

```javascript
describe('secure area', () => {
  beforeEach(() => {
    cy.login(Cypress.env('username'), Cypress.env('password'))
    cy.visit('https://the-internet.herokuapp.com/secure')
  })

  it('shows the secure area heading', () => {
    cy.get('h2').should('contain', 'Secure Area')
  })

  it('has a logout button', () => {
    cy.contains('a', 'Logout').should('have.attr', 'href', '/logout')
  })
})
```

The credentials come from `Cypress.env()`, which chapter 6 sets up; for now, create `cypress.env.json` in the project root:

```json
{
  "username": "tomsmith",
  "password": "SuperSecretPassword!"
}
```

and add it to `.gitignore`, since in a real project it holds real secrets.

Run the spec in `npx cypress open` and expand the session entry in the command log. The first test shows the session being **created** ; the second shows it **restored** , without the login form. Note that `cy.session` leaves you on a blank page, which is why `beforeEach` visits the secure page afterwards.

Some tests in a spec fail with "not logged in" even though `cy.login()` runs in `beforeEach`. The setup function ends with `cy.get('button[type=submit]').click()`. What is the most likely cause?

 `cy.session` only works with `localStorage`, not cookies The session id must be unique per test `beforeEach` runs after the test body The setup ends right after the click, so the session can be saved before the login response sets the cookie

Cypress saves the state as soon as the setup's commands finish. Ending the setup with an assertion that the login completed (a success message, a URL, a cookie) makes it wait for the real logged-in state. A `validate` function then catches a bad cache.

## Faster still: log in without the form[#](https://testingbot.com#faster-still-log-in-without-the-form)

The setup above still drives the login form once per spec. If your application has a login API, call it with `cy.request()` inside the setup instead (chapter 4), and store whatever the response gives you the way the app does: a cookie is kept automatically, a token usually goes into `localStorage`. Even the first login then skips the UI. The [`cy.session` documentation](https://docs.cypress.io/api/commands/session) has examples for both. Keep one test that logs in through the real form, so the form itself is still covered.

By default a session is cached per spec file. Passing `cacheAcrossSpecs: true` in the options shares it across all specs of the same run on the same machine, which helps large suites that log in as the same user everywhere.

Your tests log in as either "admin" or "viewer". With `cy.session(username, ...)`, what happens when a spec switches from an admin test to a viewer test?

 Each username has its own cached session; switching restores the other one (creating it the first time) The admin session is reused, because only one session can be cached per spec The test fails, because a session cannot change user

The id identifies the cached session. Different ids are different sessions, and `cy.session` clears the browser before restoring the requested one, so nothing leaks from admin into viewer.

[Previous · Chapter 5 Fixtures and Network Stubbing with cy.intercept](https://testingbot.com/resources/courses/cypress/fixtures-and-network-stubbing) [Next · Chapter 7 Cypress Configuration, Environment Variables and Retries](https://testingbot.com/resources/courses/cypress/config-and-environment-variables)

On this page

1. [A first custom command](https://testingbot.com#a-first-custom-command)
2. [Why logging in needs special treatment](https://testingbot.com#why-logging-in-needs-special-treatment)
3. [A cy.login command built on cy.session](https://testingbot.com#a-cy-login-command-built-on-cy-session)
4. [Faster still: log in without the form](https://testingbot.com#faster-still-log-in-without-the-form)

Certification

Earn the free, resume-worthy TestingBot Cypress Certification for this course.

[How it works](https://testingbot.com/resources/courses/cypress/certification)
