DEV Community

Deepak Kumar
Deepak Kumar

Posted on • Edited on

How CORS (Cross-Origin Resource Sharing) Works?

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

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

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://.
  • 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

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
Enter fullscreen mode Exit fullscreen mode

CORS header


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 or check out this video 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.

npm install cors
Enter fullscreen mode Exit fullscreen mode

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

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

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

Enter fullscreen mode Exit fullscreen mode

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. 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 | Instagram

Subscribe to my email newsletter and stay updated!

If you liked the post, give some ❤️!! Cheers

Top comments (10)

Collapse
 
artis3n profile image
Ari Kalfus

Maybe add a note to the article about how dangerous origin: "*" is outside of an example snippet?

Collapse
 
dipakkr profile image
Deepak Kumar

Hi Ari,

Thanks for your suggestion. Sure, I will add that I know it's a dangerous practice for writing origin:* in production. I just meant to describe how it works.

Really appreciate your reply !

Collapse
 
colombaseppe profile image
ColombaSeppe

Could you please explain how to fix this and why this is dangerous?

Thread Thread
 
sengz profile image
Seng

If you’re allowing origin:* in production, you’re literally allowing any script from any domain to call your server. Which for some malicious user’s intention, they may write some malicious script and hijack your system’s data security.

The way to fix it is simple, just list down the domain that you would like to whitelist instead of using the * wildcard. If you listed down the domains instead of using the wildcard, your server will only allow CORS for the whitelisted domains while reject others that is not in the list.

Hope it helps. :)

Thread Thread
 
artis3n profile image
Ari Kalfus

Seng is right. I'll add that Access-Control-Allow-Origin is only allowed to be a * for unauthenticated requests. The browser will ignore Access-Control-Allow-Credentials: true if your allow-origins header is set to a wildcard. However, this leaves you open to distributed brute force login attacks. The right thing to do would be to check the Referer/Origin header against a known whitelist of sites you allow to access, and set your Access-Control-Allow-Origin header accordingly.

Collapse
 
sbalaji98 profile image
SBalaji98

Thanks for the blog on cors, it was helpful and informative.

Collapse
 
dipakkr profile image
Deepak Kumar

Thanks !

Collapse
 
anilsingh profile image
Anil Singh

Its very useful article for me. Thank you.

Collapse
 
dipakkr profile image
Deepak Kumar

Thanks, Anil 👏

Collapse
 
sinteticwizard profile image
Ramon Ramirez

nice