CORS Explained: How to Fix "Access-Control-Allow-Origin" Errors

Published on • 10 min read

It is the rite of passage for every frontend developer. You try to fetch data from an API, and your console screams red:

Access to fetch at 'https://api.example.com/data' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

You panic. You Google it. You find a Chrome extension to bypass it. You continue development.

Stop! Ignoring CORS is dangerous. Let's understand what it actually is and how to fix it properly.

Advertisement

What is CORS?

CORS stands for Cross-Origin Resource Sharing. It is a security feature implemented by browsers to prevent malicious websites from stealing your data.

Imagine if you logged into your bank account, and then visited `evil.com`. Without CORS, `evil.com` could make a `fetch()` request to `api.yourbank.com/transfer-money` and, because your browser automatically sends your cookies, the bank might accept it!

Because of the Same-Origin Policy, browsers block this by default. CORS is the standard way to relax this policy safely.

How to Fix It Correctly

1. The Server Must Allow You

You cannot fix CORS on the frontend (in production). That is the most specific myth.

CORS errors mean the Server did not send a specific header saying, "I allow this website to talk to me."

If you own the API, you need to add this header to your response:

Access-Control-Allow-Origin: https://your-website.com

2. Using a Proxy (For Development)

If you are just developing locally, you can use a proxy to "trick" the browser into thinking the request is coming from the same origin.

In package.json (for React/Vue apps):

"proxy": "https://api.external-service.com"
Advertisement

Common Pitfalls

  • Do not set "*" in production: Setting `Access-Control-Allow-Origin: *` allows anyone to call your API. Unless it's a public API, avoid this.
  • Preflight Requests: For complex requests (like those with custom headers or DELETE methods), the browser sends an `OPTIONS` request first. Your server must handle this preflight check.

Conclusion

CORS is your friend, not your enemy. It protects your users. The next time you see that red error, remember: it's just the browser asking, "Do you have permission to be here?" And only the server can answer "Yes".