How to Fix CORS Error in Cypress Tests Quickly
CORS error in Cypress happens because the browser blocks requests to a different domain without proper permissions. To fix it, configure your backend to allow cross-origin requests or use Cypress's chromeWebSecurity: false setting in cypress.config.js to disable this security during testing.Why This Happens
CORS (Cross-Origin Resource Sharing) errors occur when your Cypress test tries to access a resource from a different domain, protocol, or port than your app's origin, and the server does not allow it. Browsers block these requests to protect users from malicious sites.
For example, if your frontend runs on http://localhost:3000 and your API is on http://localhost:5000, the browser treats this as cross-origin and blocks requests unless the API explicitly allows it.
describe('API test', () => { it('fetches data from API', () => { cy.visit('http://localhost:3000') cy.request('http://localhost:5000/data').then((response) => { expect(response.status).to.eq(200) }) }) })
The Fix
To fix CORS errors in Cypress, you can either configure your backend server to send the correct Access-Control-Allow-Origin header allowing your frontend origin, or disable Cypress's web security for testing purposes.
Disabling web security is easier but should only be used in testing, not production.
// cypress.config.js const { defineConfig } = require('cypress') module.exports = defineConfig({ e2e: { chromeWebSecurity: false, baseUrl: 'http://localhost:3000' } })
Prevention
To avoid CORS errors in the future, always configure your backend API to include proper CORS headers for your frontend domains. Use middleware like cors in Node.js or equivalent in other frameworks.
Also, keep chromeWebSecurity enabled in Cypress for production-like testing and only disable it when necessary.
Use environment variables to manage URLs and origins to keep tests flexible and maintainable.
const express = require('express') const cors = require('cors') const app = express() app.use(cors({ origin: 'http://localhost:3000' })) app.get('/data', (req, res) => { res.json({ message: 'Hello from API' }) }) app.listen(5000)
Related Errors
Other errors similar to CORS issues include:
- Mixed Content: Loading HTTP resources on an HTTPS page causes blocking. Fix by using HTTPS everywhere.
- Preflight Failures: Complex requests require OPTIONS preflight; server must handle OPTIONS method correctly.
- Invalid Headers: Missing or incorrect
Access-Control-Allow-MethodsorAccess-Control-Allow-Headerscan cause failures.
Key Takeaways
chromeWebSecurity: false in Cypress config to bypass CORS during tests, but only for testing.