DEV Community

Gandharv
Gandharv

Posted on • Updated on

WTF is CORS

Often I find people scratching their head around the definitive meaning to CORS.

How many times have you seen this error in the console?

Cross-Origin Resource Sharing (CORS)

Let's try to explain CORS by first talking about what is the ooposite of CORS i.e. same-origin policy.

In same-origin policy websites are restricted to accessing resources from the same origin through what is known as same-origin policy

But why do we need same origin policy in the first place?

Let’s say you browse to a malicious website https://stealbankbalance.com while logged into https://mysweetbank.com, stealbankbalance can essentially make AUTHENTICATED requests if the same origin policy was not in place.

What is the need for a cross-origin policy?
As web developers we know that working on a website we will make cross-origin requests to other domains too.

Let's talk about how do we fix the error.

CORS is controlled by Access-Control-Allow-Origin header.

CORS is a browser feature and checks for the response headers having the domain name or else rejects the request.

If you have control over the server you are responding from, you need to add the clients domain name in the response headers

Example: Access-Control-Allow-Origin: https://www.mydomain.com

NOTE: A server that responds Access-Control-Allow-Origin: * allows all origins which can be a large security risk.
Only use * if your application absolutely requires it such as creating an open/public API.

If you do not have access to the server response headers then need to proxy the request from your frontend server, since cors is a browser feature it will not complain if the request is passed through a server.

Top comments (0)