0
0
Cypresstesting~15 mins

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

Choose your learning style9 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.