Cypress · Browser testing end to end
How do you handle authentication in Cypress tests?
Short answer
Log in once through the UI or an API request, then reuse the session with cy.session or a saved cookie. Avoid repeating a full UI login in every test because it is slow and adds another failure point.
Authentication is setup, not the behaviour most tests care about. A full UI login in every test makes the suite slower and couples unrelated tests to the login form. The usual patterns are an API login that sets a cookie, a programmatic token, or a single UI login wrapped in cy.session.
Cypress.Commands.add("loginByApi", (email: string, password: string) => {
cy.request({
method: "POST",
url: "/api/auth/login",
body: { email, password },
}).then((response) => {
cy.setCookie("session", response.body.token);
});
});Choose the setup
- API login plus cookie: fast and stable when the backend supports it
- UI login wrapped in cy.session: realistic and cached for the spec or suite
- cy.session with validate: re-checks a cached session before reusing it
- cy.origin: required when the login provider is on another origin
- Do not hard-code production credentials; use test users from environment variables
Whichever path you choose, assert that authentication actually succeeded before the test proceeds. A silent failure to log in produces confusing downstream failures. cy.session in particular restores cookies and storage, so the assertion belongs inside the setup function.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why is an API login preferable to a UI login for setup?
- 2How does cy.session cache authentication?
- 3What if the auth provider is on another origin?
- 4Which test should still cover the login form?
Say it in the interview
I treat login as setup. The fastest stable approach is an API call that sets the session cookie, or a UI login wrapped in cy.session so it is cached. I assert that authentication succeeded before continuing, and I keep credentials in environment variables. I still keep one dedicated test for the login form, because the rest of the suite no longer exercises it.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Cypress mock interview and get scored feedback on depth, clarity and confidence.