Add custom header to Access-Control-Allow-Headers

Hi,

Access to XMLHttpRequest at 'https://sheet.best/api/sheets/' 
from origin 'https://xxxx.netlify.com' has been
blocked by CORS policy: 
Request header field x-api-key is not allowed by 
Access-Control-Allow-Headers in preflight response.

This is the error I get in my browser. How do I add x-api-key to the Access-Control-Allow-Headers ?

I have tried using both _header and netlify.toml but none worked for me.

#/public/_header
/*
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers = "x-api-key"
//netlify.toml 
[[headers]]
  for = "/*"
  [headers.values]
    Access-Control-Allow-Origin = "*"
    Access-Control-Allow-Headers = "x-api-key"

Hi, @zhex900, welcome to our Netlify community site.

I’ll do my best to answer but I’m not an expert (yet!) on CORS issues/

I believe the Access-Control-Allow-Headers header is a response header sent by the API endpoint to let you know which headers it allows.

This means the only way to change that would be to have control of the API servers (the ones which answer for the request URL of https://sheet.best/api/sheets/) and have that server modify that header. If you control those servers you can change their configuration to include the headers that you want.

If you don’t control those servers (and it sounds like this is the case), then there is no way to change this behavior.

You cannot send this in your preflight request to the API. You can send the header Access-Control-Request-Headers in a preflight check to see which headers are allowed.

There is more documentation about this here:

The usual recommended workaround for CORS issues is to proxy to the API. There is documentation about that workaround here:

Would you please take a look at that and let us know if this will solve the issue occurring in this case? If not, or if there are other questions, please let us know.

Thank you for your detailed explanation. I will give it a try and let you know the result.