CORS, what is it?

Cross-Origin Resource Sharing (CORS) is a mechanism that allows a web application running at one origin (domain) to access selected resources from a different origin using HTTP headers. Here different origin can be, different domain or protocol or ports. Cross-Origin resources can be stylesheets, scripts, iframes, APIs or any other media content like images, videos, etc.

Simply put, CORS is a standard for accessing web resources on different domains/servers/ports.

In general, web browsers have a security measure called, same-origin policy. The same-origin policy lets resources interact with resources from the same domain or port, but not with resources from a different domain or port. So, what if there is a need to access resources from a completely different domain/server or the different port on the same server? CORS is the solution.

 

When do we use CORS?

In Web development, it’s often necessary to separate the front-end application from the server-side application or remote service by hosting them on different ports of the same server or on a different server for development reasons such as different infrastructure, security, scaling, code-management, etc.

If we have resources such as Images and Videos that needs to be used on more than one website, we can host the resources on one common server and access it from different domains using CORS.

How does it work?

  1. A user opens a webpage hosted on the domain (A) to access a resource which references another domain (B), the resources here refers to Images, Stylesheets and APIs.
  2. The user’s browser creates a connection to B, adding an “Origin” HTTP header to the request which contains A’s information.
  3. B responds with an “Access-Control-Allow-Origin” HTTP header which lists the domains allowed to make CORS requests^.
  4. If A is allowed to make the request, the B responds with the requested content.

^A wildcard (“*”) allows all domains to make requests.

The Access-Control-Allow-Origin header is defined in the B’s server configuration. If the header doesn’t contain wildcard entries and A isn’t explicitly included, the user’s browser will display a preconfigured error or a generic error message.

Compatibility

CORS works on the latest versions of all major browsers such as IE11, Edge, Firefox, Chrome, Safari, Opera on Desktops and Mobile.

Please contact us to learn more and let’s build something great together!

 References

  1. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
  2. https://caniuse.com/#search=CORS
Categories: Development