CORS issue in create-react-app

Did you know malformed API url in create-react-app can cause CORS issue in Google Chrome when getting data from external api via fetch or axios.

I know this a strange issue. It is what i faced when using pixabay api in a create-react-app. I had stored api key in .env file. I made a stupid mistake of adding a semicolon as in case of a variable declaration inside .env file.

cors issue storing environment variables create react app
DO NOT ADD SEMICOLON at the end of environment variable

And i used the api key using REACT_APP_PIXABAY_API_KEY react enviroment variable in a JavaScript template string inside axios. I was getting this CORS error in browser console.

cors issue fetch api to call external api
In this API request, REACT_APP_PIXABAY_API_KEY is wrong and hence URL was malformed

It was really hard to debug the issue. I tried various CORS workarounds as mentioned in official docs including configuring proxy myself and adding http-proxy-middleware.

But still the issue wasn’t solved. I wasted nearly 2 hours on this bug. Finally when i was inspecting the console log, I found a semicolon where it shouldn’t be. It lead to an Aha! moment where i revisited the .env file and fixed the environment variable.

cors error in google chrome due to malformed api url in create react app
CORS Error due to malformed API URL

Finally I got rid of the issue and was able to get the data from the server.

So when using create-react-app, make sure your API url is formed correctly and your environment variables are correct to avoid bugs such as these.