6 Must-Know Things About Cross-Origin Resource Sharing (CORS)

GP Lee
GP Lee
Jun 17 · 5 min read
Image for post
Image for post


Without CORS, websites are restricted to accessing ONLY resources from the same domain due to same-origin policy. In other words, we could not request to API data provided by Spotify (Different Origin Server) without CORS because my site www.gplee.com is not the same origin as www.spotify.com

Image for post
Image for post

In conclusion, CORS allows for more freedom and functionality than purely same-origin request, but is more secure than simply allowing all cross-origin requests

1. What is Cross-origin resource sharing (CORS)?

CORS is a security mechanism that allows a web page from one domain or Origin to access a resource with a different domain (cross-domain request)

Without features like CORS, websites are restricted to accessing resources from the same origin through what is known as same-origin policy

There are often cases where you need to make AJAX (i.e., Axios) calls to https://api.mydomain.com or https://mydomain incorporates your Node.js server or some 3rd party fonts or analytics providers like Google Analytics. Cross-Origin Resource Sharing (CORS) enables these cross-domain requests

Allow Cross domain request, bypassing same-origin policy

Image for post
Image for post

2. What is same-origin policy?

The same-origin policy is a critical security mechanism that restricts how a document or script loaded from one origin can interact with a resource from another origin

It helps isolate potentially malicious document, reducing possible attack vectors such as CSRF attack

same-origin policy is security model for web application

Image for post
Image for post

3. What is Cross-domain vulnerability?

By restricting HTTP calls to only ones to the same origin (i.e., the browser tab’s domain), same-origin policy closes some hacker backdoors such as Cross-Site Request Foregery (CSRF) (CSRF tokens are still necessary)

Browsers allow websites to store information on a client’s computer, in the form of cookies

Image for post
Image for post

Pros of cookies [in the context of CORS]

  • Browser stores the cookie (information such as name of the cookie, when it was created, user information …) So whenever the user makes a request to a domain on which this cookie is accessible, the cookie would be sent to the server for that domain
  • No need to keep retrieving user information from the server; convenient that we can store and retrieve information on and from the client-side (user’s browser)
Cookie: cookiename=chocolate;
Path=/ [// ;otherDdata]

Cons of cookies [in the context of CORS]

  • malicious-site.com can send those cookies to your-bank.com , without the user knowing
  • If you visit the malicious site, and same-origin policy was not there, the malicious user can place an order to transfer $1,000 dollars from your account to his account and you might do not like this😞

4. What is the definition of ‘origin’?

At this point, Someone might wonder the definition of origin 🤔

Origin includes the combination of protocol, domain, and port. In other words,

The following URLs are different origins

https://www.google.com vs. https://www.api.google.comhttp://localhost:9000 vs. http://localhost:8080

While the following URLs are same origins

Image for post
Image for post

5. How CORS works

There are 2 types of CORS requests

  1. simple requests
  2. preflighted requests

1.Simple requests

CORS request that does not require a preflight request

Step 1

A browser tab open to https://www.mydomain.com initiates AJAX request GET to https://api.domains.com/widgets

Step 2

Along with adding headers like Host , the browser automatically adds the Origin Request Header for cross-origin requests

Step 3

The server checks the Origin request header. If the Origin value is allowed, it sets the Access-Control-Allow-Origin to the value in the request header Origin

Step 4

When the browser receives the response, the browser checks the Access-Control-Allow-Origin header to see if it matches the origin of the tab

If not, the response is blocked

Access-Control-Allow-Origin: * allows all origins
--> a large security risk

2. Preflighted requests

A preflighted request is a CORS request where the browser is required to send a preflight request before sending the request being preflighted to ask the server permission if the original CORS request can proceed

Any CORS request has to be preflighted if

  • AJAX call to POST JSON data to a REST API meaning the Content-Type header is application/json → RESTful API request
  • AJAX call to an API which uses a token to authenticate the API in a request header such Authorizationauthorized request using token

Step 1

The browser sends the OPTIONS request first (aka the preflight request)

Step 2

The server respond back specifying the allowed HTTP methods and headers. If the original CORS request intended to send a header or HTTP method not in the list, failed

Step 3

Since the headers and method pass the check 200 OK , the browser sends the original CORS request ( Origin header in the request)

Step 4

The response has the correct origin in Access-Control-Allow-Origin header so checks pass and control is handed back to the browser tab

6. How to implement CORS using Node.js

*Implementing the request headers to set up CORS is different for langauges and backend framework*

We are going to use Node.js / Express.

Step 1

Install CORS middleware:

$ npm install cors

And that’s it!

JavaScript In Plain English

Enjoyed this article? If so, get more similar content by subscribing to our YouTube channel!

JavaScript In Plain English

New articles every day.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store