Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add a request header to a CORS preflight request?

I have a website that accesses an API from an external server (not the server that serves the website) via a plain XmlHttpRequest (see below). That API requires an API key for accessing the service to be added as request header. However, as these are CORS requests the browser first does a preflight request to check if that server supports CORS. Now, it seems that the server also wants to see the API key in these preflight requests that are done by the browser. Is it possible to pass the API key also to the preflight request?

const req = new XMLHttpRequest();
req.open("GET", "https://some/api/endpoint");
req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
req.setRequestHeader("x-api-key", _apiKey);
req.onload = () => {
  // ...
};
req.send();
like image 875
Michael Avatar asked Jan 25 '23 16:01

Michael


1 Answers

The CORS preflight OPTIONS request is totally controlled by the browser; so it’s not possible to add request headers to it. See https://fetch.spec.whatwg.org/#cors-preflight-fetch. That’s why any endpoint you send requests to must be set up to allow unauthenticated OPTIONS requests, and respond to them with a 200 OK (at least as long as a request triggers a preflight, which it always will if you add custom request headers, such as the x-api-key header in the question).

like image 138
sideshowbarker Avatar answered Jan 28 '23 10:01

sideshowbarker