Archive: adding a CORS header for a Netlify static file
This is a 2022 record of a CORS configuration I used for a static JSON file on Netlify. Netlify configuration and browser behaviour change. Treat the examples as historical context and confirm the current documentation before applying them.
The problem
The file opened in a browser, but a request from another origin produced this error:
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.
The issue was a missing Access-Control-Allow-Origin response header for the path being requested.
Scope the permission first
Access-Control-Allow-Origin: * permits any origin to read a response that browsers can access. Apply it only to data intended for public cross-origin use. It does not make a private resource safe.
A _headers file
One option was a _headers file in the published directory. The shape of the rule was:
/path/to/directory/* Access-Control-Allow-Origin: *
My JSON file was under /transparent/code/id.json, so the path-specific rule was:
/transparent/code/* Access-Control-Allow-Origin: *
A netlify.toml rule
I also recorded the rule in netlify.toml at the project root:
...
[[headers]]
for = "/path/to/directory/*"
[headers.values]
Access-Control-Allow-Origin = "*"
...
For the JSON path in this example, it became:
...
[[headers]]
for = "/transparent/code/*"
[headers.values]
Access-Control-Allow-Origin = "*"
...
Confirm current precedence and deployment behaviour in Netlify's headers documentation before relying on this approach.
What the header changed
A browser's same-origin policy constrains cross-origin requests. A server can opt into a permitted cross-origin response by returning CORS headers. The browser then evaluates those headers against the requesting origin and request type.
For current explanations and implementation details, use MDN's CORS guide.