What is CORS, and How to Bypass It?

Learn how CORS controls cross-origin requests with key headers, challenges, best practices, and real-world examples. Use Requestly to test, debug, and manage CORS policies efficiently without backend changes.

Get Started free
What is CORS, and How to Bypass It
Home Guide What is CORS, and How to Bypass It?

What is CORS, and How to Bypass It?

Web applications often need to interact with resources from different websites or servers. For example, your website might request data from an external API or load images from another site.

This process, known as cross-origin communication, can be risky if not managed correctly. That’s where Cross-Origin Resource Sharing (CORS) comes in. CORS is a security feature built into web browsers to control which websites or applications can access resources from another domain.

This article explains how CORS works, why it’s important, and how to set it up correctly with clear examples and common pitfalls.

What is CORS?

Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers to control how resources on a web server can be requested from a domain (origin) other than the one serving the web page.

It allows servers to specify who can access their resources and which requests are permitted by sending specific HTTP headers. This mechanism helps safely relax the strict Same-Origin Policy (SOP), which by default blocks cross-origin requests to protect users from malicious sites trying to steal data or perform unauthorized actions.

What is the Same-Origin Policy (SOP)?

The Same-Origin Policy is a critical security concept that restricts how documents or scripts loaded from one origin can interact with resources from another origin. An origin is defined by the scheme (protocol), host (domain), and URL port.

Under SOP, a web page can only make requests to the same origin it was loaded from. This prevents malicious scripts on one page from obtaining access to sensitive data on another page through that page’s Document Object Model.

How Does CORS Work?

CORS uses special HTTP headers that tell browsers which websites or applications can access a resource. When your browser tries to get data from a different website, it includes an Origin header that tells the server where the request is coming from. The server then decides whether to share the data by sending back specific CORS headers.

CORS Headers

These CORS headers either allow the request or block it. If the request is allowed, the browser continues to load the data. If not, the browser stops the request to keep your data safe.

Simple Requests

Some requests are considered “simple” and don’t need extra permission checks. These usually include:

  • GET, HEAD, or POST requests
  • No custom headers except for Accept, Accept-Language, Content-Language, or Content-Type
  • If Content-Type is used, it must be application/x-www-form-urlencoded, multipart/form-data, or text/plain

For these simple requests, the browser sends the request directly to the server with the Origin header. If the server allows it, the browser loads the data.

Preflight Requests

Other requests, like those with custom headers or using methods like PUT or DELETE, need an extra check called a preflight request. This preflight request uses the OPTIONS method to ask the server if it’s okay to make the actual request.

The browser includes headers like Access-Control-Request-Method and Access-Control-Request-Headers to tell the server about the real request. The browser performs the real request if the server responds with the correct CORS headers.

What are the Types of CORS Request Headers?

When a browser makes a cross-origin request, it includes specific headers to share essential details:

  • Origin: Shows where the request is coming from.
  • Access-Control-Request-Method: In preflight requests, tells the server what method (like PUT or DELETE) the real request will use.
  • Access-Control-Request-Headers: In preflight requests, lists any custom headers that the real request will use.

What are the Important CORS Response Headers?

When your server sends a response to a browser that made a cross-origin request, you must include specific headers to tell the browser if it can access the data and how. Here’s what each header does and how to use it:

1. Access-Control-Allow-Origin

Use this header to tell the browser which websites can access the data. You can set it to a specific origin (like https://frontend.example.com) or * (all origins, which is not secure for sensitive data).

Example in a server response:

Access-Control-Allow-Origin: https://frontend.example.com

2. Access-Control-Allow-Methods

Use this header to tell the browser which HTTP methods (like GET, POST, PUT) are allowed when accessing the resource. This helps control what kind of actions can be performed.

Example:

Access-Control-Allow-Methods: GET, POST

3. Access-Control-Allow-Headers

Use this header to specify which custom headers can be sent with the request (like X-Custom-Header). This is important when you have specific needs for authentication or tracking.

Example:

Access-Control-Allow-Headers: Content-Type, Authorization

4. Access-Control-Allow-Credentials

Use this header to allow the browser to include cookies or authentication tokens with the request. Set it to true and make sure you also specify a trusted origin (not *).

Example:

Access-Control-Allow-Credentials: true

5. Access-Control-Max-Age

This header tells the browser how long (in seconds) it can store the preflight response in its cache. This helps reduce extra network requests for similar actions.

Example:

Access-Control-Max-Age: 86400

6. Access-Control-Expose-Headers

Use this header to tell the browser which headers from the server’s response can be seen by JavaScript in the browser. Usually, only a few safe headers are visible.

Example:

Access-Control-Expose-Headers: X-Custom-Header

When you set these headers on your server’s responses, you control how and if the browser shares the data with other websites or applications. These headers help you set clear boundaries about who can access your data and how they can use it.

Benefits of Using CORS

CORS is crucial for modern web applications that often interact with services or APIs hosted on different servers. Without CORS, the browser’s security restrictions would block these cross-origin interactions. Here’s how CORS helps:

  • Enables Secure Data Sharing: CORS allows web applications to access resources hosted on other domains while following strict rules. This prevents malicious sites from making unauthorized requests.
  • Supports API Integrations: Many applications rely on third-party APIs to fetch data. CORS allows users to securely connect to these APIs without running into browser security errors.
  • Improves User Experience: By enabling safe cross-origin requests, CORS lets your application provide richer, more dynamic content to users, like integrating maps, payment gateways, or social media feeds.
  • Controls Access Clearly: The server defines CORS policies, so you can decide exactly which domains or applications are allowed to use your resources.

HTTP Interceptor Banner

Best Practices for Implementing CORS

Implementing CORS needs careful consideration to avoid unnecessary risks or compatibility issues. Here’s what you should keep in mind:

  • Set Clear Policies: Use the Access-Control-Allow-Origin header to specify trusted origins. Avoid using * unless necessary, as it grants broad access.
  • Limit HTTP Methods: Only allow the HTTP methods (like GET, POST, PUT) that your application needs. Define them using the Access-Control-Allow-Methods header.
  • Control Custom Headers: If your application uses custom headers, declare them explicitly with the Access-Control-Allow-Headers header. This prevents unintended exposure of sensitive data.
  • Use Short Cache Durations: The Access-Control-Max-Age header lets you control how long the browser caches preflight responses. Keep this duration short to quickly reflect changes in your policy.
  • Be Consistent Across Environments: CORS issues often arise when environments (like local development vs. production) have mismatched policies. Make sure your configurations are consistent and tested in all environments.
  • Check Browser Compatibility: Some older browsers handle CORS differently. Test across different browsers to avoid issues for users.
  • Review and Update Policies: Your application’s security needs can change over time. Review your CORS settings regularly and update them as needed.

Common CORS Errors and Fixes

Here are common problems and how to fix them:

  • Missing Access-Control-Allow-Origin Header: Ensure your server sends this header to let the browser know who can access the resource.
  • Incorrect Credentials Handling: When you use credentials, avoid setting Access-Control-Allow-Origin to *. Use the specific trusted origin.
  • Preflight Failures: If preflight requests fail, check that your server responds to OPTIONS requests with the right CORS headers.
  • Mismatched Methods or Headers: Make sure the server’s allowed methods and headers match what the browser wants to send.

Real-World Example of CORS

Let’s say you have a web application hosted at https://bstakdemo.com that needs to fetch test results from an API at https://browserstack.com.

By default, your browser won’t let bstakdemo.com access data from browserstack.com because they’re from different origins. Browsers block these cross-origin requests to protect user data.

Here’s how CORS helps:

  1. User Action: A user on https://bstakdemo.com clicks a button to get the latest test results from https://browserstack.com.
  2. CORS Request: The browser sees this is a cross-origin request and automatically includes the Origin header showing https://bstakdemo.com as the source.
  3. BrowserStack Response: If https://browserstack.com allows requests from https://bstakdemo.com, it adds Access-Control-Allow-Origin: https://bstakdemo.com in its response headers.
  4. Browser Validation: The browser checks this header to confirm that the response is allowed.
  5. Access Granted: The response data is now available to the JavaScript code on bstakdemo.com, which can show the test results to the user.

If https://browserstack.com doesn’t allow requests from https://bstakdemo.com, the browser blocks the response, preventing sensitive data from reaching an unauthorized site.

How Requestly Helps with CORS During Development and Testing

Handling CORS policies can be challenging during development, especially when working with multiple services or APIs hosted on different domains. Requestly bridges the gap between frontend development and backend CORS configuration, making cross-origin testing faster and less error-prone.

Here is how Requestly plays a role in the CORS workflow:

  • Testing CORS behavior: You can simulate cross-origin requests by rewriting headers or redirecting requests to different domains. This helps verify if your server’s CORS settings work as expected without changing the backend.
  • Bypassing CORS restrictions: During development, if you face CORS errors because the server isn’t set up yet or you want to test APIs from another origin, Requestly lets you bypass or modify headers temporarily.
  • Debugging CORS issues: It lets you inspect and change request and response headers on the fly. This helps pinpoint where CORS policies might be failing or misconfigured.
  • Mocking APIs: You can mock responses for cross-origin requests to test frontend behavior without needing the actual backend, which is useful when APIs are unavailable.

Talk to an Expert

Conclusion

CORS controls how web applications access resources from different domains, protecting users and data from security risks. It uses specific headers in requests and responses to allow or block cross-origin interactions based on server policies.

Requestly simplify handling CORS during development and testing. It lets developers modify HTTP requests and responses directly in the browser to test, debug, or bypass CORS restrictions without backend changes. This makes identifying and fixing CORS issues faster and easier and ensures smoother cross-origin communication before deploying applications.

Try Requestly for Free

Tags
Automation Testing Cross browser testing Testing Tools Website Testing

Get answers on our Discord Community

Join our Discord community to connect with others! Get your questions answered and stay informed.

Join Discord Community
Discord