Member-only story
React With CORS: The How and the Why
Make a request to a server on a different domain

Like many others, I have recently started to build something. I decided to create a web app that scratches an itch I have felt for quite some time. Also, I wanted to increase my knowledge of React and some core Ruby libraries. Therefore, I am implementing this as a React SPA and the server is a Rack app. I am not using any Ruby framework but only small and very specialized libraries. I decided to write down the things I learned to increase my learning experience and let others join in on that experience.
This first article is about Cross-Origin Resource Sharing (CORS).
What Is CORS?
CORS is a technique that allows you to make an ajax request to a server of a different domain. This is very useful if you want to consume an API directly on your client — something that is absolutely needed if you’re writing a Jamstack web app.
But this can be useful in other use cases as well. If you put your front end on a domain different than the back-end domain, you need to make the back end available to the front end per CORS — which is exactly my use case.
Let’s explore the why and how!
How Does CORS Work Under the Hood?
We first have to think about the reason why this is even necessary. Every single browser has a security mechanism called “Same origin policy.” This mechanism makes sure that a possible evil script can’t execute some random API call to a random domain.
What is considered same origin?
By definition, the protocol
, the port
, and the host
have to be equal to be considered as the same origin. This makes it clear that you can call any route on your server with any query parameters, but you can't call to another subdomain since a subdomain is a different host.
So https://my-awesome-app.com
can't access https://api.my-awesome-app.com
because the host is different, but https://my-awesome-app.com/api/v1/...
with any route is always available.
How can we deactivate the same-origin policy for our server/client?