</>

Technology

Cypress

Difficulty

Intermediate

Interview Question

How do you handle login in Cypress without going through the UI every time?

Answer

Bypass UI Login in Cypress

Going through the UI for login on every test is slow. The best approach is to hit the login API directly and set the token.

Method 1: cy.request() + localStorage

JavaScript
// cypress/support/commands.js
Cypress.Commands.add('loginViaApi', (email, password) => {
  cy.request({
    method:  'POST',
    url:     `${Cypress.env('apiUrl')}/auth/login`,
    body:    { email, password },
    failOnStatusCode: false,
  }).then((response) => {
    expect(response.status).to.equal(200)
    // Store token so the app recognizes the session
    window.localStorage.setItem('authToken', response.body.token)
    window.localStorage.setItem('user', JSON.stringify(response.body.user))
  })
})

// In test
beforeEach(() => {
  cy.loginViaApi('test@automateqa.com', 'Test@123')
  cy.visit('/dashboard')
})

Method 2: cy.session() — Cache Session Across Tests (Cypress 9+)

JavaScript
// cypress/support/commands.js
Cypress.Commands.add('login', (email, password) => {
  cy.session(
    [email, password],          // cache key
    () => {
      // This block only runs once per session key
      cy.visit('/login')
      cy.get('#email').type(email)
      cy.get('#password').type(password)
      cy.get('[data-testid="login-btn"]').click()
      cy.url().should('include', '/dashboard')
    },
    {
      validate: () => {
        // Confirm session is still valid before reusing it
        cy.getCookie('session_id').should('exist')
      },
    }
  )
})

// In test file
describe('Dashboard Tests', () => {
  beforeEach(() => {
    cy.login('test@automateqa.com', 'Test@123')  // uses cached session
    cy.visit('/dashboard')
  })

  it('should show user profile', () => {
    cy.get('[data-testid="user-name"]').should('contain', 'QA Tester')
  })
})

Method 3: Set Cookie Directly

JavaScript
Cypress.Commands.add('loginWithCookie', () => {
  cy.request('POST', '/api/auth/login', {
    email:    Cypress.env('username'),
    password: Cypress.env('password'),
  }).then((response) => {
    // Set auth cookie Cypress received
    cy.setCookie('auth_token', response.body.token)
  })
})

cypress.config.js — Credentials via env

JavaScript
module.exports = defineConfig({
  env: {
    username: 'test@automateqa.com',
    password: 'Test@123',
    apiUrl:   'https://api.automateqa.online',
  },
})

Benefits

  • 80–90% faster than UI login on every test
  • Tests are independent — each starts with a clean authenticated session
  • No flakiness from login page rendering

Follow AutomateQA

Related Topics