How To Bypass Cors In Electron Development

How To Bypass Cors In Electron Development

I was working on an Electron application that needed to make API requests to check license keys and allow license key activation. The problem I encountered during development was when making API requests to an external website its server was blocking my requests because I did not have CORS enabled on the API server. I’m not going to get into the details of CORS, or Cross Origin Resource Sharing, but it’s an area of concern for client-side applications in the browser making requests to third party domains.

If my API requests were coming from a server then this wouldn’t be an issue because CORS does not apply to server to server requests. Since the project was scaffold using Create-React-App and during the development phase the app loads in a browser instance on http://localhost:3000 so any requests are made in a browser context using Chromium’s networking layer where CORS becomes applicable.

How to get around CORS?

You could enable CORS on your server by setting Access-Control-Allow-Origin: * but this is frowned upon because you are enabling your server to respond to any requests from any other domain.

I was able to get around my issue by using a proxy service called cors-anywhere. Just prefix your API call with https://cors-anywhere.herokuapp.com and this endpoint will make your API request on your behalf and return the response.

DO NOT USE THIS FOR PRODUCTION

fetch(
  "https://cors-anywhere.herokuapp.com/https://www.example.com/?" +
    new URLSearchParams({
      action: "activate_license",
      license: license
    }),
  {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    }
  }
)
  .then(response => {
    return response.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error("error", error);
  });