Blog Image

Fix: Cloudflare - Access to XMLHttpRequest from origin has been blocked by CORS policy:

Cross-Origin Resource Sharing (CORS) errors occur when a web application attempts to access resources from a different domain without proper permissions. Cloudflare, a popular CDN and security provider, may inadvertently cause or exacerbate CORS issues due to its security and caching features. This guide outlines the steps to resolve CORS errors when using Cloudflare.


1. Check Cloudflare Security Rules

Cloudflare may apply security rules that block or challenge requests, potentially triggering a JavaScript challenge or entirely blocking the request.

  1. Log in to your Cloudflare dashboard.
  2. Navigate to the Firewall section.
  3. Review the Security Rules and look for:
    • Firewall Rules
    • Bot Management settings
    • Browser Integrity Check
  4. Temporarily disable or adjust any rules that might block the CORS-related requests. For example:
    • Disable JavaScript challenges for your API domain.
    • Lower the security level for the API route (if necessary).

2. Disable Cloudflare for the Desired Domain

To determine if Cloudflare is causing the issue, you can temporarily disable it for your domain.

  1. Go to the DNS settings in your Cloudflare dashboard.
  2. Locate the DNS record (e.g., A or CNAME) associated with your domain or subdomain.
  3. Click the Cloud icon next to the record to turn it gray (bypassing Cloudflare).
  4. Save your changes.

This action routes traffic directly to your origin server without passing through Cloudflare, allowing you to test if the CORS error persists.


3. Use Cloudflare Transformation Rules to Modify Response Headers

Cloudflare allows you to rewrite response headers using Transformation Rules. This can help you set the appropriate CORS headers for your requests.

  1. In the Cloudflare dashboard, navigate to Rules > Transform Rules.
  2. Create a new Response Header Modification rule:
    • Condition: Define when the rule should apply (e.g., requests to your API endpoint).
    • Action: Add or overwrite CORS headers, such as:
      Access-Control-Allow-Origin: *
      Access-Control-Allow-Methods: GET, POST, OPTIONS
      Access-Control-Allow-Headers: Content-Type, Authorization
      
  3. Save the rule and deploy it.

4. Wait for Changes to Take Effect

Cloudflare changes, especially DNS updates, may take a few minutes to propagate. Allow time for your updates to become active before re-testing your application.


5. Use a CORS Proxy

If none of the above steps resolve the CORS issue, you can use a free proxy service such as corsproxy.io.

  1. Create an account (free tier available).
  2. Prefix your API requests with the CORS Proxy URL. For example:
    https://corsproxy.io/?url=<domain>
    

Create a free Account to fix CORS Errors in Production

Say goodbye to CORS errors and get back to building great web applications. It's free!

App screenshot