Search code examples
corssuperagent

Which server must implement CORS?


The superagent documentation contains this entry about CORS:

For security reasons, browsers will block cross-origin requests unless the server opts-in using CORS headers. Browsers will also make extra OPTIONS requests to check what HTTP headers and methods are allowed by the server. Read more about CORS.

The .withCredentials() method enables the ability to send cookies from the origin, however only when Access-Control-Allow-Origin is not a wildcard ("*"), and Access-Control-Allow-Credentials is "true".

However, it does not explain which server needs to implement CORS.

There are two servers that (I think) it could refer to:

  • The web server which sends the HTML and JavaScript to the browser
  • The API / resource server that the delivered JavaScript makes a request to

Which server must implement CORS?


Solution

  • The API / resource server that the delivered JavaScript makes a request to is the one that needs to enable CORS support — assuming that server is running at an origin that’s different than the origin of the frontend JavaScript code that’s making the request.

    The server which sends the HTML and JavaScript to the browser doesn’t need to enable CORS — assuming what you mean is the server that’s the origin of the frontend code making the request.

    The reason that web server doesn’t need to enable CORS is that you’re not making any cross-origin requests to that server. Instead it’s just serving your frontend JavaScript code.

    But any other server at some other origin to which your frontend JavaScript code makes a request must enable CORS — otherwise your browser will block your frontend JavaScript code accessing the response body and response headers of any response that other server sends.

    https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS has more details.