How to Handle Authentication in Cypress Tests Correctly
To handle authentication in Cypress, avoid logging in through the UI for every test. Instead, use
cy.request() to perform a programmatic login by sending credentials directly to the backend, then set the authentication token or cookie before visiting protected pages.Why This Happens
Many beginners try to log in by typing username and password in the UI for every test. This causes slow tests and flaky failures because UI login depends on many elements and network calls.
javascript
describe('Login test', () => { it('logs in via UI', () => { cy.visit('/login') cy.get('#username').type('user') cy.get('#password').type('pass') cy.get('button[type=submit]').click() cy.url().should('include', '/dashboard') }) })
Output
Test runs slowly and sometimes fails if login UI changes or network is slow.
The Fix
Use cy.request() to send login credentials directly to the backend API. Then save the authentication token or cookie. This skips the UI login and makes tests faster and more reliable.
javascript
describe('Programmatic login', () => { beforeEach(() => { cy.request('POST', '/api/login', { username: 'user', password: 'pass' }) .then((response) => { expect(response.status).to.eq(200) cy.setCookie('auth_token', response.body.token) }) }) it('visits dashboard after login', () => { cy.visit('/dashboard') cy.contains('Welcome').should('be.visible') }) })
Output
Test runs fast and reliably with direct backend login.
Prevention
Always prefer programmatic login in Cypress tests to avoid flaky UI login steps. Use environment variables for credentials and create custom commands for reuse. Keep authentication logic in one place to simplify maintenance.
- Use
cy.request()for login API calls. - Store tokens or cookies with
cy.setCookie(). - Create custom Cypress commands for login.
- Use environment variables for sensitive data.
Related Errors
Common related errors include:
- 401 Unauthorized: Happens if token or cookie is not set correctly before visiting protected pages.
- Cross-Origin Errors: Occur if login API is on a different domain and CORS is not configured.
- Flaky UI Login: Caused by slow network or UI changes.
Fix these by ensuring tokens are set properly, configuring CORS, and avoiding UI login in tests.
Key Takeaways
Use cy.request() to perform programmatic login instead of UI login.
Set authentication tokens or cookies directly to maintain session.
Create reusable custom commands for login to keep tests clean.
Avoid UI login to make tests faster and less flaky.
Use environment variables to manage sensitive login data securely.