'How to enable CORS on a Netlify deployment?

I'm using Netlify to serve some static .json files. They load fine in the browser but when I try to fetch them via javascript I get the following error in the console:

Access to fetch at (redirected from ) from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I checked all the options in my site's settings in the Netlify dashboard and don't see any options to enable CORS, how can this be done?



Solution 1:[1]

Add a file called _headers next to your index.html with the following content:

/*
  Access-Control-Allow-Origin: *

It's better to change it to your actual origin instead of * in production.

Solution 2:[2]

The better approach is using a proxy like this,

Create a file called netlify.toml in the root directory of the project. (i.e. next to index.html)

[[redirects]]
  from = "/<path-to-access-cors-url>"
  to = "<cross-origin-url>"
  status = 200
  force = true
  headers = {X-From = "Netlify"}
[[headers]]
  for = "/*"
  [headers.values]
    Access-Control-Allow-Origin = "*"

Now use the URL in your HTTP request like this, https://your-domain.com/<path-to-access-cors-url>

Example:

Consider, fakedomain.com is your domain and you want to request resources from https://example.com/patha

[[redirects]]
  from = "/pathx"
  to = "https://example.com/patha"
  status = 200
  force = true
  headers = {X-From = "Netlify"}
[[headers]]
  for = "/*"
  [headers.values]
    Access-Control-Allow-Origin = "*"

Now use the URL in your HTTP request like this, https://fakedomain.com/pathx

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Raj Yadav