What is CORS (Cross-Origin Resource Sharing)

If you’ve ever worked with APIs in the browser, you probably saw this error:

Access to fetch at ‘https://api.example.com/data from origin ‘http://localhost:3000 has been blocked by CORS policy

This happens because of CORS — Cross-Origin Resource Sharing.


Why CORS Exists

Browsers follow the same-origin policy for security.
It means that scripts loaded from one origin (domain, protocol, port) cannot freely access resources from another.
Otherwise, any website could secretly read your banking data if you’re logged in.

CORS is a mechanism that allows servers to say:

“Yes, I trust requests from this origin.”


Example of CORS

Imagine you have a frontend app at http://localhost:3000 and an API at https://api.example.com.

Without CORS configured, your browser will block requests.
To fix this, the server must add a header:

Access-Control-Allow-Origin: http://localhost:3000

You can also allow all origins (less secure):

Access-Control-Allow-Origin: *

Common CORS Headers

  • Access-Control-Allow-Origin — which origins can access
  • Access-Control-Allow-Methods — allowed HTTP methods (GET, POST, PUT…)
  • Access-Control-Allow-Headers — custom headers that are allowed
  • Access-Control-Allow-Credentials — whether cookies can be included

Conclusion

CORS is not a bug, it’s a security feature.
If you see CORS errors, you need to configure your API server, not the browser.
The key idea: the server explicitly decides which external clients are trusted.