How CORS (Cross-Origin Resource Sharing) Works? 
Tags: webdev, javascript, tutorial, node
Published: 2019-12-17 19:27:41

If you are a web developer, you must have seen the '**CORS**' error appearing often on your screen when you try to call the API.  But, Why does it happen?

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/y38l053yjayw0e3m8e04.png)

Well, For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, if you want to access your API hosted at `https://api.github.com` from your client-side frontend application which is hosted at `https://example.com`. The browser will not allow this request to complete. 

You only need to think about CORS when :

1. API accessed by the browser.
2. API is hosted on a separate domain.

![CORS Same Origin](https://thepracticaldev.s3.amazonaws.com/i/6boak0gpa976zx4qfy15.png)

So, why does it happens? 

The browsers enforce a security feature called `Same Origin Policy`. According to `Same Origin Policy`, the Same Origin calls are allowed and Different Origin calls are not allowed. 


Uhh !! What is this Same Origin, Different Origin? Let's see this more in detail. Browsers define the `Origin` as a combination of `Scheme`, `Host`, and `Port`. 


- **Scheme name** — It is the protocol to be used to access the resource on the Internet. The scheme names followed by the three characters `://` .The most commonly used protocols are `http://`, `https://`, `ftp://`, and `mailto://`.

<br/>


- **Hostname** — It is the address of the host where the resource is located. A hostname is a domain name assigned to a host computer. This is usually a combination of the host's local name with its parent domain's name. For example, `www.dev.to` consists of the host's machine name `www` and the domain name `dev.to`

<br/>


- **Port Number** — Port is a communication endpoint where your application run. For more information about Port Number. Check out this [Link](https://en.wikipedia.org/wiki/Port_(computer_networking).

If these three combinations of **Scheme, Hostname, and Port** are same then the browser identifies it as the Same Origin. And, the request gets complete. 


> So, Does it means that it is impossible to make `Cross-Origin HTTP request` ??

The answer is NO. 

That's where the **CORS** comes into picture, Cross-Origin Resource Sharing mechanism. 

----

### How CORS Works

CORS allows the server to explicitly whitelist certain origin and help to bypass the `same-origin` policy. 

If your server is configured for CORS, it will return an extra header with "Access-Control-Allow-Origin" on each response.

For example, if my API server hosted at `https://api.dipakkr.com/users` is CORS configured and I am making a request from my client application `https://github.com` to fetch some data. The response will have this header.


```
Access-Control-Allow-Origin: https://github.com
```

![CORS header](https://thepracticaldev.s3.amazonaws.com/i/szdr3sdbyu2m38ptj01h.png)


----


### CORS Preflight Request 
`Preflighted` requests first send an HTTP request by the `OPTIONS` method to the resource on the other domain, to determine if the actual request is safe to send or not. 


You can read more about CORS Preflight request at [MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests) or check out this [video](https://www.youtube.com/watch?v=tcLW5d0KAYE) by Akshay Saini. 


----

### How to Enable CORS

For enabling CORS on your server application. You need two things. 

1. First, you need to determine the origins of whitelist.

2. Second, you have to add the CORS middleware to the server.


Here, I am explaining to you the steps to configure CORS on your NodeJS server. 

First install the `cors` npm package from this [link](https://www.npmjs.com/package/cors). 

```
npm install cors
```

Then go to your server application and add the below code. 

```javascript
// require the cors package
var cors = require('cors');

// enables cors
app.use(
  cors({
    origin: "*",
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    preflightContinue: false
  })
);

```

Here you can see I am using `origin: "*"` which means any domain can access this application. 

> **Please note that it is dangerous to put `origin:"*"` in a production application and you should never do that**. 


To know more about CORS, please visit [MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). It's a great place for web developers. 

If you read till last, don't forget to give your feedback in the comments. Getting feedback helps me improve. 

I write about new stuffs almost daily. You can follow me on [Twitter](https://twitter.com/diipakkr) | [Instagram](https://instagram.com/diipakkr)

[Subscribe to my email newsletter and stay updated!](https://dipakkr.substack.com/)

If you liked the post, give some :heart:!! Cheers