Bird
Raised Fist0
Cypresstesting~15 mins

Programmatic login (cy.request) in Cypress - Deep Dive

Choose your learning style10 modes available
Overview - Programmatic login (cy.request)
What is it?
Programmatic login using cy.request in Cypress means logging into a web application by sending a direct HTTP request instead of interacting with the login page manually. This method bypasses the user interface and directly authenticates the user by calling the backend login API. It is faster and more reliable because it avoids UI delays and flakiness. This technique helps tests start with an authenticated session quickly.
Why it matters
Without programmatic login, tests must go through the login page every time, which slows down test runs and can cause failures due to UI changes or slow loading. Programmatic login solves this by making tests faster and more stable, allowing developers to focus on testing real features instead of wasting time on repetitive login steps. It also reduces test maintenance and improves confidence in test results.
Where it fits
Before learning programmatic login, you should understand basic Cypress commands, HTTP requests, and how authentication works in web apps. After mastering this, you can explore advanced session management, token handling, and custom commands to reuse login logic efficiently.
Mental Model
Core Idea
Programmatic login uses a direct backend request to authenticate, skipping the user interface to speed up and stabilize tests.
Think of it like...
It's like having a special key to open a locked door directly instead of knocking and waiting for someone to open it.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Test Script   │──────▶│ cy.request()  │──────▶│ Backend Login │
│ (no UI steps) │       │ sends HTTP    │       │ API validates │
└───────────────┘       │ login data    │       │ credentials   │
                        └───────────────┘       └───────────────┘
                                │                      │
                                ▼                      ▼
                        ┌───────────────┐       ┌───────────────┐
                        │ Receives      │◀──────│ Returns       │
                        │ auth token    │       │ auth token    │
                        └───────────────┘       └───────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding Cypress HTTP Requests
🤔
Concept: Learn how Cypress can send HTTP requests directly to servers using cy.request.
Cypress has a command called cy.request that lets you send HTTP requests like GET, POST, PUT, etc., to any URL. This is useful to interact with backend APIs without using the browser UI. For example, you can send a POST request to a login endpoint with username and password.
Result
You can send and receive HTTP responses inside your tests, allowing backend communication.
Knowing cy.request lets you bypass the UI and interact directly with backend services, opening up faster and more reliable testing options.
2
FoundationBasics of Web Authentication
🤔
Concept: Understand how web apps authenticate users using credentials and tokens.
Most web apps require users to log in by sending credentials (like username and password) to a server. The server checks these and returns an authentication token or cookie that proves the user is logged in. This token is then sent with future requests to access protected pages.
Result
You understand that login is about exchanging credentials for a token that grants access.
Grasping authentication basics helps you see why programmatic login works by mimicking this token exchange.
3
IntermediateImplementing Programmatic Login with cy.request
🤔Before reading on: do you think programmatic login requires visiting the login page UI? Commit to your answer.
Concept: Use cy.request to send login credentials directly to the backend and store the authentication token.
Instead of visiting the login page and typing credentials, you send a POST request to the login API endpoint with the username and password. The server responds with an auth token or cookie. You then save this token in Cypress so subsequent requests or page visits are authenticated.
Result
Tests start with a logged-in state instantly, skipping UI login steps.
Understanding that you can authenticate by directly calling the backend API saves time and reduces test flakiness.
4
IntermediateManaging Authentication Tokens in Cypress
🤔Before reading on: do you think Cypress automatically uses tokens from cy.request for all future page visits? Commit to your answer.
Concept: Learn how to store and apply authentication tokens or cookies after programmatic login.
After receiving the auth token or cookie from cy.request, you must save it using Cypress commands like cy.setCookie or cy.setLocalStorage. This ensures the browser session is authenticated when visiting pages. Without this, the app won't recognize the user as logged in.
Result
Authenticated sessions persist across test steps, enabling seamless testing of protected pages.
Knowing how to manage tokens bridges the gap between backend login and frontend session state.
5
AdvancedCreating Custom Commands for Reusable Login
🤔Before reading on: do you think repeating cy.request login code in every test is efficient? Commit to your answer.
Concept: Encapsulate programmatic login logic into a Cypress custom command for reuse.
You can create a custom Cypress command, e.g., cy.login(), that performs the cy.request login and token storage. This command can be called in any test to quickly authenticate. It reduces code duplication and centralizes login logic for easier maintenance.
Result
Tests become cleaner and easier to maintain with reusable login commands.
Understanding custom commands improves test organization and scalability.
6
ExpertHandling Token Expiry and Session Refresh
🤔Before reading on: do you think a token obtained once will always keep the session valid? Commit to your answer.
Concept: Learn strategies to handle token expiration and refresh during long test suites.
Auth tokens often expire after some time. Tests running long or in parallel may face expired tokens. Experts implement logic to detect expired tokens and re-run programmatic login or refresh tokens automatically. This ensures tests don't fail due to stale authentication.
Result
Tests remain stable and authenticated even with token expiry challenges.
Knowing how to handle token lifecycle prevents flaky tests and improves reliability in real-world scenarios.
Under the Hood
When cy.request sends a login POST request, it directly communicates with the backend server's authentication API. The server verifies credentials and returns an authentication token or sets a session cookie in the HTTP response headers. Cypress captures this response and allows the test to store the token or cookie in the browser context. This bypasses the UI rendering and JavaScript login flows, making authentication faster and less error-prone.
Why designed this way?
Cypress was designed to test web apps end-to-end but recognized that UI-based login is slow and flaky. Programmatic login via cy.request was introduced to speed up tests by interacting directly with backend APIs. This design balances realistic testing with practical speed and stability. Alternatives like UI login were slower and more brittle, while direct backend calls provide a reliable shortcut.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ cy.request()  │──────▶│ Backend Login │──────▶│ Auth Token or │
│ sends POST   │       │ API validates │       │ Cookie in     │
│ with creds   │       │ credentials   │       │ HTTP response │
└───────────────┘       └───────────────┘       └───────────────┘
        │                        │                       │
        ▼                        ▼                       ▼
┌───────────────┐       ┌───────────────────────────────┐
│ Cypress Test  │◀──────│ Stores token/cookie in browser │
│ receives     │       │ context for authenticated state │
│ response     │       └───────────────────────────────┘
└───────────────┘
Myth Busters - 3 Common Misconceptions
Quick: Does cy.request automatically set cookies for future page visits? Commit to yes or no.
Common Belief:cy.request automatically applies cookies or tokens from the response to all future browser requests.
Tap to reveal reality
Reality:cy.request does not automatically set cookies or local storage in the browser; you must manually save and apply them for authenticated sessions.
Why it matters:Tests may fail because the app does not recognize the user as logged in, causing confusion and wasted debugging time.
Quick: Is programmatic login less secure because it bypasses the UI? Commit to yes or no.
Common Belief:Programmatic login is insecure because it skips the UI and might expose credentials or tokens.
Tap to reveal reality
Reality:Programmatic login uses the same backend authentication API as the UI and is as secure; it just automates the process for testing purposes.
Why it matters:Misunderstanding this can prevent teams from adopting faster, more reliable testing methods.
Quick: Will a token obtained once always keep the session valid? Commit to yes or no.
Common Belief:Once logged in programmatically, the session token never expires during tests.
Tap to reveal reality
Reality:Tokens often expire or become invalid, requiring re-login or token refresh to maintain session validity.
Why it matters:Ignoring token expiry leads to flaky tests that fail unpredictably, wasting time and reducing trust in test results.
Expert Zone
1
Some apps use HttpOnly cookies that cannot be set via JavaScript, requiring cy.request to handle cookies carefully to maintain session.
2
Programmatic login may need to handle multi-factor authentication or CAPTCHA by mocking or bypassing these steps in test environments.
3
Parallel test runs require isolated sessions; experts use unique tokens or separate storage to avoid cross-test interference.
When NOT to use
Programmatic login is not suitable when testing the login UI itself or when the authentication flow includes complex UI interactions like CAPTCHA or social logins. In such cases, UI-based login tests or specialized tools should be used.
Production Patterns
In real-world projects, teams create reusable custom commands for programmatic login, integrate token refresh logic, and combine programmatic login with UI tests for full coverage. They also store tokens securely and mock external auth services to speed up CI pipelines.
Connections
API Testing
Programmatic login builds on API testing by sending HTTP requests directly to backend endpoints.
Understanding API testing helps grasp how programmatic login interacts with backend services without UI, improving test speed and reliability.
Session Management
Programmatic login relies on session management concepts like cookies and tokens to maintain authenticated state.
Knowing session management clarifies how authentication tokens persist user identity across requests in tests.
Network Protocols
Programmatic login uses HTTP protocol mechanics to send requests and receive responses.
Understanding HTTP methods, headers, and cookies deepens comprehension of how programmatic login communicates with servers.
Common Pitfalls
#1Assuming cy.request sets authentication cookies automatically.
Wrong approach:cy.request({ method: 'POST', url: '/login', body: { username: 'user', password: 'pass' } }); cy.visit('/dashboard');
Correct approach:cy.request({ method: 'POST', url: '/login', body: { username: 'user', password: 'pass' } }) .then((response) => { cy.setCookie('session_id', response.body.sessionId); }); cy.visit('/dashboard');
Root cause:Misunderstanding that cy.request does not automatically apply cookies or tokens to the browser session.
#2Hardcoding credentials in multiple tests without reuse.
Wrong approach:In every test: cy.request({ method: 'POST', url: '/login', body: { username: 'user', password: 'pass' } });
Correct approach:Cypress.Commands.add('login', () => { cy.request({ method: 'POST', url: '/login', body: { username: 'user', password: 'pass' } }) .then((response) => { cy.setCookie('session_id', response.body.sessionId); }); }); // In tests: cy.login();
Root cause:Not using custom commands leads to duplicated code and harder maintenance.
#3Ignoring token expiration causing test failures.
Wrong approach:cy.login(); // Run many tests assuming token never expires
Correct approach:function login() { return cy.request({ method: 'POST', url: '/login', body: { username: 'user', password: 'pass' } }) .then((response) => { cy.setCookie('session_id', response.body.sessionId); }); } beforeEach(() => { login(); });
Root cause:Not accounting for token lifecycle leads to flaky tests when tokens expire.
Key Takeaways
Programmatic login with cy.request bypasses the UI to authenticate users faster and more reliably.
You must manually handle authentication tokens or cookies after cy.request to maintain session state.
Creating reusable custom commands for login improves test maintainability and clarity.
Handling token expiration is crucial for stable, long-running test suites.
Programmatic login is a powerful technique but should not replace UI login tests when testing the login flow itself.

Practice

(1/5)
1. What is the main benefit of using cy.request for programmatic login in Cypress?
easy
A. It logs in faster by skipping the UI steps.
B. It visually shows the login process in the browser.
C. It requires manual input of username and password each time.
D. It disables cookies to improve security.

Solution

  1. Step 1: Understand what cy.request does

    cy.request sends HTTP requests directly without interacting with the UI.
  2. Step 2: Identify the benefit in login context

    By using cy.request for login, tests skip slow UI steps and run faster.
  3. Final Answer:

    It logs in faster by skipping the UI steps. -> Option A
  4. Quick Check:

    Programmatic login = faster login without UI [OK]
Hint: Programmatic login skips UI, making tests faster [OK]
Common Mistakes:
  • Thinking cy.request shows UI login
  • Assuming manual input is needed every time
  • Believing cookies are disabled automatically
2. Which of the following is the correct syntax to perform a POST login request using cy.request in Cypress?
easy
A. cy.request('GET', '/login', { username: 'user', password: 'pass' })
B. cy.request('/login', 'POST', { username: 'user', password: 'pass' })
C. cy.request({ url: '/login', method: 'GET', body: { username: 'user', password: 'pass' } })
D. cy.request('POST', '/login', { username: 'user', password: 'pass' })

Solution

  1. Step 1: Recall cy.request method signature

    The correct order is cy.request(method, url, body) for POST requests.
  2. Step 2: Check each option

    cy.request('POST', '/login', { username: 'user', password: 'pass' }) matches the correct syntax with method 'POST', URL '/login', and body object.
  3. Final Answer:

    cy.request('POST', '/login', { username: 'user', password: 'pass' }) -> Option D
  4. Quick Check:

    Method first, then URL, then body [OK]
Hint: Remember: method, URL, then body in cy.request [OK]
Common Mistakes:
  • Swapping method and URL order
  • Using GET instead of POST for login
  • Passing body with GET method
3. Given the following code snippet, what will be the value of token after the test runs?
cy.request('POST', '/api/login', { username: 'test', password: '1234' })
  .then((response) => {
    const token = response.body.token
    cy.wrap(token).as('authToken')
  })
medium
A. Undefined, because token is declared inside the callback only.
B. The token string returned from the login API response body.
C. An error because cy.wrap cannot be used inside then.
D. The entire response object instead of just the token.

Solution

  1. Step 1: Understand cy.request and then callback

    The then receives the response object from the POST request.
  2. Step 2: Extract token from response.body.token

    The code assigns token to the token string from the response body and saves it as an alias.
  3. Final Answer:

    The token string returned from the login API response body. -> Option B
  4. Quick Check:

    Response body token is saved as alias [OK]
Hint: Response body holds token; alias saves it for later [OK]
Common Mistakes:
  • Thinking token is undefined outside callback
  • Believing cy.wrap cannot be used inside then
  • Confusing response object with token string
4. You wrote this code to login programmatically but your test fails because the session is not preserved:
cy.request('POST', '/login', { username: 'user', password: 'pass' })
cy.visit('/dashboard')

What is the most likely reason?
medium
A. You forgot to save and set the authentication cookie or token after login.
B. The cy.visit command must come before cy.request.
C. The login API endpoint does not support POST requests.
D. You need to add cy.wait() between the commands.

Solution

  1. Step 1: Understand session preservation in Cypress

    After login via cy.request, you must save cookies or tokens to keep the session.
  2. Step 2: Identify missing step in code

    The code does not save or set any authentication cookie or token before visiting the dashboard.
  3. Final Answer:

    You forgot to save and set the authentication cookie or token after login. -> Option A
  4. Quick Check:

    Session needs saved cookie/token after login [OK]
Hint: Save auth cookie/token after login to keep session [OK]
Common Mistakes:
  • Assuming cy.visit order matters here
  • Thinking login API rejects POST requests
  • Adding unnecessary waits instead of fixing session
5. You want to create a reusable Cypress command for programmatic login that stores the token and sets it as a cookie for later tests. Which code snippet correctly achieves this?
hard
A. Cypress.Commands.add('login', () => { cy.request('GET', '/api/login') .then((res) => { cy.setCookie('authToken', res.body.token) }) })
B. Cypress.Commands.add('login', () => { cy.visit('/login') cy.get('#username').type('user') cy.get('#password').type('pass') cy.get('button[type=submit]').click() })
C. Cypress.Commands.add('login', () => { cy.request('POST', '/api/login', { username: 'user', password: 'pass' }) .then((res) => { cy.setCookie('authToken', res.body.token) }) })
D. Cypress.Commands.add('login', () => { cy.request('POST', '/api/login', { user: 'user', pass: 'pass' }) .then((res) => { cy.setCookie('authToken', res.body.token) }) })

Solution

  1. Step 1: Check HTTP method and payload correctness

    Login usually requires POST with correct keys; Cypress.Commands.add('login', () => { cy.request('POST', '/api/login', { username: 'user', password: 'pass' }) .then((res) => { cy.setCookie('authToken', res.body.token) }) }) uses 'username' and 'password' correctly.
  2. Step 2: Verify token storage and cookie setting

    Cypress.Commands.add('login', () => { cy.request('POST', '/api/login', { username: 'user', password: 'pass' }) .then((res) => { cy.setCookie('authToken', res.body.token) }) }) sets the cookie 'authToken' with the token from response body, enabling session reuse.
  3. Step 3: Review other options for errors

    Cypress.Commands.add('login', () => { cy.visit('/login') cy.get('#username').type('user') cy.get('#password').type('pass') cy.get('button[type=submit]').click() }) uses UI login, not programmatic. Cypress.Commands.add('login', () => { cy.request('GET', '/api/login') .then((res) => { cy.setCookie('authToken', res.body.token) }) }) uses GET instead of POST. Cypress.Commands.add('login', () => { cy.request('POST', '/api/login', { user: 'user', pass: 'pass' }) .then((res) => { cy.setCookie('authToken', res.body.token) }) }) uses wrong keys 'user' and 'pass'.
  4. Final Answer:

    Reusable command with POST request, correct keys, and cookie set. -> Option C
  5. Quick Check:

    POST + correct keys + setCookie = reusable login [OK]
Hint: Use POST with correct keys and setCookie for token [OK]
Common Mistakes:
  • Using GET instead of POST for login
  • Wrong payload keys like 'user' instead of 'username'
  • Trying UI login instead of programmatic
  • Not setting cookie after login
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard