Call me : +20 102743 8103
How I Solved That Annoying CORS Error

So picture this:
You’ve just finished setting up your frontend. The UI looks clean, buttons work, and now it’s time to connect it to your shiny new backend API. You hit that first fetch()
call, and then boom — red text in the console:
“Access to fetch at ‘http://yourapi.com/data‘ from origin ‘http://localhost:3000‘ has been blocked by CORS policy.”
This happened to me recently (again). And even though I’ve dealt with CORS errors before, it always takes a second to remember why it’s happening — and how to fix it without breaking something else.
Let me walk you through what I did, what worked, and a few things I learned the hard way.
🔍 So, what is CORS anyway?
CORS stands for Cross-Origin Resource Sharing. It’s a browser security feature that prevents your frontend (served from one domain) from making requests to a backend hosted on another domain — unless the server explicitly allows it.
It sounds annoying, but it’s actually protecting users from some serious attacks.
🧪 The Setup That Caused the Error
- Frontend: React app on
localhost:3000
- Backend: Express server on
localhost:5000
- Request: Fetching JSON data from
/api/posts
The browser sees this as a cross-origin request and blocks it unless the backend sends the right headers.
✅ How I Fixed It (The Express Way)
In my Express server, I installed the cors
package:
bashnpm install cors
Then added this to the top of my index.js
:
jsconst cors = require('cors');
app.use(cors());
Boom. Just like that, the error was gone. But — this opens your API to all origins, which is fine for dev, but not always okay in production.
🛡️ A Safer CORS Setup for Production
Instead of allowing everything, I restricted it to my frontend domain:
jsconst corsOptions = {
origin: 'https://myfrontend.com',
optionsSuccessStatus: 200,
};
app.use(cors(corsOptions));
Now only requests from https://myfrontend.com
are accepted — much safer.
⚙️ Other Workarounds (For Testing Only)
- Using a proxy:
In development, I sometimes set up a proxy invite.config.js
orcreate-react-app
to route API calls through the frontend server. - Using a CORS proxy:
If I’m testing something quickly, services likehttps://cors-anywhere.herokuapp.com/
let you bypass CORS altogether (not recommended for anything serious though).
💡 Lesson Learned
Every time I run into a CORS issue, I remind myself: it’s not a bug, it’s a security feature. And fixing it means understanding how your backend is configured, not just hacking around it.
If you’re stuck with a similar issue, try the simple solution first — but make sure you lock it down before going live.
Let me know if you’ve ever had a weird CORS case or a clever way of solving it — I’m always curious how other devs deal with it.