When developing a website/web app on localhost which makes requests to another server, you might run into Cross Origin Resource Sharing (CORS) issues. I won’t go into too much detail about what CORS is in this post. All I will say is that CORS exists for security reasons, but when you’re developing locally it can be a pain! You can read more about CORS on the MDN docs.
I have written this simple guide to explain the main solutions for disabling cross origin restrictions on localhost (and therefore fixing any CORS errors whilst developing your app locally), which I will explain in more detail below.
Create React App comes with a config setting which allows you to simply proxy API requests in development. This is available in
email@example.com. To do this add the proxy setting to your package.json like this
This is a really simple solution which might not work with more complicated situations where multiple API's are involved, or certain types of API authentication is needed.
You can directly disable CORS in the browser. If you do this, please be aware that you are disabling security restrictions which are there for a reason. I wouldn’t recommend browsing the web with CORS disabled; Just disable it whilst developing your website/app.
The most reliable way to disable CORS in the latest version of Chrome on Mac (tested on v84) is to run it with web security disabled.
- Force quit Chrome by going to the mac menu and pressing “force quit” (or pressing command Q).
- Then run this command to open Chrome with web security disabled
open -n -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome — args — user-data-dir=”/tmp/chrome_dev_test” — disable-web-security
Once you’re done developing, restart Chrome and it will go back to normal.
The easiest and most reliable way to disable CORS in Firefox is to install the CORS Everywhere plugin.
The easiest and most reliable way to CORS in Safari is to disable CORS in the develop menu.
- Enable the develop menu by going to Preferences > Advanced.
- Then select “Disable Cross-Origin Restrictions” from the develop menu.
Once you’re done developing, restart Safari and it will go back to normal.
Alternatively you could use a proxy like cors-anywhere.
If you want to easily demo cors-anywhere, Rob — W has setup a public demo which is great for consuming public API's as it requires no registration or config https://cors-anywhere.herokuapp.com. As it’s just a demo, requests are limited.
To use the public demo of cors-anywhere, just add the url you want to make the request to after the domain e.g. https://cors-anywhere.herokuapp.com/https://cat-fact.herokuapp.com/facts (*if you view this in the browser you might get an error about a missing request header. When you make an API request using in your app using something like Axios or Fetch this won’t be an issue).
If you found this useful, have any questions, or want more content like this, feel free to follow me on twitter!