Understanding same-origin policy and enable CORS for local development with react

Lets consider the following scenario where a malicious website is trying to cheat you by faking transactions to your bank website

In step 4: A malicious website is reading cookies from some other website. This is bad as once malicious website has this data, it cannot differentiate between the good user and a fake user.

To stop this from happening, browsers implement same-origin policy. What this basically means is that to make a second request, first being the home page, the second request must be from the same origin as the destination.

Source: https://en.wikipedia.org/wiki/Same-origin_policy

In local development, same-origin policy can be an issue. Consider this scenario:

When we go to http://localhost:3000 and this page makes a request for port 4000, it would go into preflight (more on preflight here and here).

To avoid this, there are several solutions we can use:

My personal preference is proxies as it requires little code. If written right, this change has little chance to affect your production code.

Option 1: HAProxy

On the mac, you can install haproxy via brew

brew install haproxy

This is how my haproxy file looks like at the root of our react project

Once this is done, we need to start 3 servers:

Now if we visit http://localhost:9000 haproxy will handle CORS for us.

Option 2: Built in proxies

Many boiler plates come with proxies as part of the code. We are using React-Redux-Starter-Kit and this uses koa-proxy. All we have to do is enable it. Following are the contents of the file at “config/_development.js”

Now all we have to do is

Now if we visit http://localhost:3000, things would work with no issues.

Senior Staff Engineer @freshworks. Ex-McKinsey/Microsoft/Slideshare/SAP, Tech Enthusiast, Passionate about India. Opinions are mine

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store