Working around CORS in create-react-app

Working around CORS in create-react-app

One problem we often face as frontend developers is dealing with CORS when making API requests.

What is CORS?

CORS (Cross-Origin Resource Sharing) is essentially a mechanism that allows a server to express what other domains can make requests to it. For example, my app could be hosted on http://domain-a.com, so only requests made from that same domain are allowed. If another app hosted on http://domain-b.com tried to make a request to http://domain-a.com, it would fail depending on the CORS policy.

Where does CRA fit in?

While using CRA (create-react-app), I've often run into a situation where I want to test my local changes against another team's API endpoint. I mean, there's only so much mocking you can rely on! By default, CRA runs locally on http://localhost:3000, so if I try to make an API request out to http://domain-a.com/users.json, CORS would block it. However, when developing locally, CRA lets us get around this by proxying all unknown requests to a specified domain. This can now help us make sure our frontend code lines up with the backend's responses.

What's the workaround?

All we need to do is add one new field in package.json. For example:

"proxy": "http://domain-a.com",

After you restart your CRA dev server, you should now be free to make requests to http://domain-a.com/users.json. This will of course only work locally and you should only make requests to a dev API endpoint, not production. That's it!

Want to see more?

I mainly write about real tech topics I face in my everyday life as a Frontend Developer. If this appeals to you then feel free to follow me on Twitter: https://twitter.com/cmacdonnacha

Bye for now 👋

Â