Skip to content

Cypress cy.request() CORS Error Fix

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about Cypress cy.request() CORS Error Fix. We cover key concepts, practical examples, and best practices.

Your cy.request() call to the API server fails with a CORS error — but cy.request() is supposed to bypass CORS. The issue is usually a server-side redirect or misconfigured base URL.

The Problem

// WRONG — request to a different origin without proper config
cy.request('POST', 'https://api.example.com/login', {
  email: 'test@example.com',
  password: 'test123'
});
CypressError: cy.request() failed on https://api.example.com/login
The response we received from your web server was:

401 Unauthorized

Or if there is a redirect:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.example.com/login

cy.request() sends an actual HTTP request and does NOT run JavaScript in the browser. It bypasses CORS, but server-side redirects or authentication failures still surface as errors.

Step-by-Step Fix

1. Verify the API URL and authentication

// RIGHT — pass authentication headers
cy.request({
  method: 'POST',
  url: 'https://api.example.com/login',
  body: { email: 'test@example.com', password: 'test123' },
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
}).then((response) => {
  expect(response.status).to.eq(200);
  cy.wrap(response.body.token).as('authToken');
});

2. Use cy.request to set up state, not test APIs

// RIGHT — use cy.request for setup, then test UI flows
before(() => {
  cy.request('POST', '/api/test-setup', {
    scenario: 'user-with-orders',
    email: 'alice@test.com'
  });
});

it('shows order history', () => {
  cy.visit('/login');
  cy.get('[data-cy=email]').type('alice@test.com');
  cy.get('[data-cy=password]').type('password');
  cy.get('[data-cy=login]').click();
  cy.get('[data-cy=orders]').should('contain', 'Order #123');
});

3. Handle redirects manually

// RIGHT — disable follow redirect to inspect the redirect
cy.request({
  method: 'GET',
  url: '/api/resource',
  followRedirect: false
}).then((response) => {
  expect(response.status).to.eq(302);
  expect(response.headers.location).to.eq('/login');
});

4. Configure baseUrl correctly

// cypress.config.js
const { defineConfig } = require('cypress');

module.exports = defineConfig({
  e2e: {
    baseUrl: 'http://localhost:3000'
  }
});

Relative URLs in cy.request() resolve against baseUrl. If baseUrl is set incorrectly, requests go to the wrong origin.

Expected output:

  ✓ logs in via API (234 ms)
  ✓ sets up test state via request (156 ms)

Prevention Tips

  • Use baseUrl in Cypress config to avoid hardcoding URLs
  • Use cy.request() for state setup, not for testing API behavior
  • Handle redirects explicitly with followRedirect: false
  • Check server logs when cy.request() returns unexpected status codes
  • Always call .then() on cy.request() to access the response

Common Mistakes with request error

  1. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  2. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  3. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks

These mistakes appear frequently in real-world CYPRESS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Does cy.request() actually bypass CORS?

Yes. cy.request() sends a raw HTTP request from Node.js, not from the browser. It is not subject to browser CORS restrictions. If you see a CORS error from cy.request(), the server is likely doing a redirect that triggers browser CORS enforcement.

Should I use cy.request() or cy.intercept() for API testing?

Use cy.request() for setup and teardown — creating test data, logging in, cleaning up. Use cy.intercept() to spy on and stub network requests that the browser makes during UI tests. Together they cover both backend and frontend testing needs.

How do I pass authentication tokens from cy.request() to UI tests?

Save the token with cy.wrap(response.body.token).as('token') and access it in later tests with cy.get('@token'). Pass it as an Authorization header or store it in localStorage depending on how your app handles auth.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro