DEV Community

Ben Subendran
Ben Subendran

Posted on

Understanding CORS and Web Origins

In the realm of web development, the terms "origin" and "CORS" frequently come into play, especially when dealing with modern web applications that make use of APIs. This short article aims to demystify these concepts for both seasoned developers and newcomers.

What is an Origin?
In the context of web security, the origin is a combination of three components: the scheme (protocol), the hostname, and the port. For two resources to share the same origin, all three of these components must match.

For instance, consider the two URLs:

http://localhost:3000
http://localhost:8000

While both have the same scheme (http) and hostname (localhost), their port numbers differ (3000 vs. 8000). Thus, they are treated as different origins by web browsers.

Why does Origin Matter?
The distinction of origin is crucial because of the Same-Origin Policy (SOP). This web security policy ensures that web pages from one origin cannot access data in another origin without explicit permission. The SOP acts as a protective barrier, preventing malicious sites from reading sensitive data from another site.

However, modern web applications often require the ability to communicate across origins, especially with the rise of microservices and third-party APIs. This is where CORS (Cross-Origin Resource Sharing) comes into play.

Understanding CORS
CORS is a security feature implemented by web browsers that controls how web pages in one origin can request resources from another origin. It's the mechanism that allows or denies web pages to make requests to a different domain than the one that served the web page.

By default, web pages cannot make cross-origin requests. But servers can specify who can access their resources by setting specific HTTP headers.

For example, if a server wants to allow its resources to be accessed by a web page served from http://localhost:3000, it can include the following header in its responses:

Access-Control-Allow-Origin: http://localhost:3000

If a web page from any other origin tries to access the resource, the browser will block the request, thus maintaining security.

The image below displays the error encountered when a client request is blocked due to the browser's CORS policy.

CORS Error example

A pivotal part of CORS is the "preflight request." Before dispatching certain types of requests (e.g., a POST request with specific headers), browsers initiate a preliminary "preflight" request using the OPTIONS HTTP method. This request essentially seeks permission for the subsequent main request, verifying whether it's allowed.

If the server doesn't respond affirmatively to the preflight, indicating that the actual request is permissible, browsers will block the main request. The error "preflight request doesn't pass access control check" is symptomatic of such a situation.

Top comments (0)