← Back to library
Cypressauthintermediatev10+
Login via API in beforeEach
Use a custom API login command in beforeEach — 10× faster than UI login and keeps tests independent.
1// cypress/support/commands.js
2Cypress.Commands.add('loginViaApi', (email, password) => {
3 // API login skips the UI entirely — much faster and more reliable
4 cy.request('POST', '/api/login', { email, password }).then(({ body }) => {
5 window.localStorage.setItem('auth_token', body.token);
6 });
7});
8
9// ── In any spec file ──────────────────────────────────────────
10describe('Protected pages', () => {
11 beforeEach(() => {
12 cy.loginViaApi('user@test.com', 'secret');
13 cy.visit('/dashboard');
14 });
15
16 it('shows the user menu', () => {
17 cy.get('[data-testid="user-menu"]').should('be.visible');
18 });
19
20 it('can access the settings page', () => {
21 cy.visit('/settings');
22 cy.get('h1').should('contain.text', 'Settings');
23 });
24});#beforeEach#API login#custom command#auth#fast login