0
0
Cypresstesting~5 mins

Token-based authentication in Cypress

Choose your learning style9 modes available
Introduction

Token-based authentication helps tests log in users safely without typing passwords every time.

When you want to test pages that need a logged-in user.
When you want faster tests by skipping the login form.
When you want to reuse the login token across many tests.
When testing APIs that require a token to access data.
Syntax
Cypress
cy.request({
  method: 'POST',
  url: '/api/login',
  body: { username: 'user', password: 'pass' }
}).then((response) => {
  const token = response.body.token;
  cy.setCookie('auth_token', token);
});

Use cy.request() to call the login API and get the token.

Store the token in a cookie or local storage for later use.

Examples
Simple POST request to login and save token in a cookie.
Cypress
cy.request('POST', '/api/login', { username: 'alice', password: '1234' })
  .then((res) => {
    cy.setCookie('auth_token', res.body.token);
  });
Store token in local storage instead of cookie.
Cypress
cy.request({
  method: 'POST',
  url: '/api/login',
  body: { username: 'bob', password: 'abcd' },
  headers: { 'Content-Type': 'application/json' }
}).its('body.token').then((token) => {
  cy.visit('/');
  cy.window().then((win) => {
    win.localStorage.setItem('token', token);
  });
});
Sample Program

This test logs in once using the API to get a token, saves it in a cookie, then visits a protected page that needs login.

Cypress
describe('Token-based Authentication Test', () => {
  before(() => {
    cy.request('POST', '/api/login', { username: 'testuser', password: 'testpass' })
      .then((response) => {
        expect(response.status).to.eq(200);
        expect(response.body).to.have.property('token');
        cy.setCookie('auth_token', response.body.token);
      });
  });

  it('Visits protected page with token', () => {
    cy.visit('/dashboard');
    cy.contains('Welcome, testuser').should('be.visible');
  });
});
OutputSuccess
Important Notes

Always check the API response status and token presence before using it.

Store tokens securely and clear them after tests to avoid side effects.

Use environment variables for usernames and passwords to keep tests safe.

Summary

Token-based authentication lets tests log in quickly without UI steps.

Use cy.request() to get tokens from login APIs.

Store tokens in cookies or local storage to access protected pages or APIs.