What is Cors and Why it matters

What is Cors and Why it matters

What is CORS?

Resource sharing with cross-origin origin (CORS) is a browser feature that allows controlled access to resources outside of the domain. It permits web pages to request resources to domains that are different from the domain that hosts the website.

CORS helps to prevent malicious websites from making unauthorized requests on behalf of the user. Without CORS, a malicious website could potentially make requests to a sensitive API on behalf of the user, potentially revealing sensitive information or causing unintended actions to be taken.

Let’s try to understand it with a simple example, try below code snippet in you browser console

fetch("https://dummy.restapiexample.com/api/v1/employees")
.then(response => response.json())
.then(data => console.log(data))

You will get the following error

Access to fetch at ‘dummy.restapiexample.com/api/v1/employees’ from origin ‘codecave.abhishekjnvk.in’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

now try on same origin(domain)

fetch("https://codecave.abhishekjnvk.in/sample.json")
.then(response => response.json())
.then(data => console.log(data))

You will get the below response

{status: ‘success’}

Did you notice the difference? The first request was made to a different domain. The second request was made to the same domain. The first request was blocked by CORS, while the second request was allowed. Lets understand why this happened.

This is because all modern browsers enforce a security feature same-origin policy which prevents a web page from making requests to a different domain than the one that served the web page. This is done to prevent malicious websites from making unauthorized requests on behalf of the user and to prevent sensitive information from being leaked.

Now that we know what CORS is, let’s take a look at how it works. We’ll also explain how to handle CORS and how to prevent unauthorized access to your API.

How Browsers Blocks CORS

When you make a request to a different domain, browser will preflight request to server checking if “Access-Control-Allow-Origin” header is set or not. If the header is not present or if it doesn’t include the domain that is whitelisted by server, the browser will block the request.

Preflight requests are an important part of the CORS process. It is a OPTION request that is sent by the browser as a part of actual request to check whether the request is allowed by the server’s security policies. Read more about preflight requests here.

Following is the flow of CORS request in browser CORS request in browser

If you like this article, don't forget to share it with your friends and colleagues.