Why is programmatic login better than login through the UI?
Programmatic login is better because it is faster than the form and does not depend on it: for most tests login is only a precondition. The cy.request call repeats the form's request and Cypress puts Set-Cookie from the response into the browser, so a broken form does not fail the whole suite. The result is cached with cy.session, and one separate test checks the form itself.
Cypress · Sessions and isolation
The “Sign in” button broke and a hundred tests fell that checked something else entirely. How do you avoid that?
A suite of a hundred tests, each starting with a login through the form. One morning the selector of the password field changed on the form and the whole suite is red although the balance, the history and the profile work. The lesson is about why login as preparation is better done programmatically, with the form checked separately.
How it works and why. A test checks one thing and the login is only a precondition for it. If the precondition goes through the UI, any broken form, slow animation or markup change fails all tests, and the report does not make clear what exactly broke. A programmatic login sends the same request the form sends, but directly: cy.request sends a POST to the sign-in endpoint and Cypress puts the Set-Cookie of the response into the browser. Then cy.session caches the result and later tests do not repeat the request.
Two ways to prepare state
Login through the form
Every test opens the sign-in page, types the fields and waits for the redirect. A test that checks the balance goes red when the “Sign in” button breaks.
Login through the API and cy.session
The signed-in state is prepared by a request without the UI and restored from the cache. One separate test checks the form.
Example: from the form to a request.
// before: in every beforeEach
cy.visit('/login');
cy.get('[data-cy=email]').type('qa@example.com');
cy.get('[data-cy=password]').type('secret');
cy.contains('button', 'Sign in').click();
// after: a request instead of the form
cy.request('POST', '/api/auth/login', {
email: 'qa@example.com',
password: 'secret',
});
cy.visit('/dashboard');
The second variant does not open the sign-in page, does not wait for a redirect and does not depend on the form markup. In a real suite it is wrapped in cy.session and the password comes from cy.env rather than the test file. The form itself is checked by one test: fields, validation, the error for a wrong password and the redirect.
Example: a token in localStorage and the session cache. If the app keeps sign-in not in a cookie but in a token, the cy.request response changes nothing in the browser by itself: the token has to be written to the storage by hand. It is convenient to do it in the session setup, so the entry is restored together with the session, while validate checks that the token is still valid.
Cypress.Commands.add('loginByApi', (email, password) => {
cy.session(
['api', email],
() => {
cy.request('POST', '/api/auth/login', { email, password })
.its('body.token')
.then((token) => {
cy.window().then((win) => {
win.localStorage.setItem('token', token);
});
});
},
{
validate() {
// a 401 on /api/me means the token has expired
cy.request('/api/me');
},
},
);
});
beforeEach(() => {
cy.env(['PASSWORD']).then(({ PASSWORD }) => {
cy.loginByApi('qa@example.com', PASSWORD);
});
cy.visit('/dashboard');
});
Here the session key contains the email, so different users do not share the cache. The token in localStorage ends up in the saved session because cy.session stores localStorage together with cookies. If /api/me returns 401, cy.request fails, validate fails with it and Cypress runs setup again. The password in the example comes from cy.env: Cypress.env() was removed in Cypress 16.
Limits and alternatives. A programmatic login needs an endpoint that can be called from a test. When sign-in goes only through an external provider with a captcha or MFA, teams often create a test endpoint or a test user with a simpler sign-in; the last resort is cy.origin in one test. Test credentials must be separate and not from production. Also an API login bypasses the form, so if the form breaks only its own test will notice: that test must not be skipped.
The approach is the same: login through the API, the result is saved in storageState and one separate test checks the UI login.
Common mistakes.
- A login through the form in every
beforeEach: the suite is slow and one broken form turns everything red. - A programmatic login without a separate test of the form: nobody will notice a broken form.
- Passwords in the test text or the repository: keep them in environment variables or
cy.env. - A login through
cy.requestto a different origin than the app: the cookie lands where the app does not expect it.
Check yourself
All tests log in through the API, the sign-in form broke and the suite is green. Is that good?
Answer
No, it is a gap. An API login bypasses the form, so only a separate UI sign-in test would notice the break. That test must stay: it checks the form, validation and the redirect.
Why is the browser already logged in after cy.request('POST', '/api/auth/login', …)?
Answer
Cypress applies the cookies from the cy.request response to the browser. If sign-in relies on a cookie, the next cy.visit opens the page of a logged-in user at once. A token in localStorage must be written separately.
cy.env, agree a test sign-in for an external provider and keep cy.origin for a single test.