DEV Community

Discussion on: What you should know about CORS

Collapse
 
chrisfosterelli profile image
Chris Foster

Awesome post Nicolas! I really like your description of how the whole process works. I wanted to share a thought on this piece here you might find interesting:

This is often a source of confusion for newcomers because it's not immediately apparent what CORS is supposed achieve. Firstly CORS is not a security measure in itself, it's actually the opposite: CORS is a way to circumvent the "Same Origin Policy" which is the security measure preventing you from making ajax requests to a different domain.

I agree this is true for the CORS headers, but I think CORS itself means something more general. There is a lot of terminology confusion here community-wide, so I try to go by the spec. Formally any request with an Origin header is a "CORS Request", regardless of what headers are present on the response. The CORS Protocol specification applies to CORS Requests and outlines both when and when not to allow CORS Requests to take place.

AFAIK there is no formal specification for the "same-origin policy", but different specs outline various cross-origin limitations (including those from the CORS Protocol) which is the term the browser error kind of lumps them together under.

Based on that I believe it is technically correct to say that the CORS Protocol is a security measure in itself. However the headers component of the CORS Protocol is definitely a way to circumvent the same-origin policy which I think might have been aligned with what you had in mind for that paragraph.

Thanks again for sharing!

Collapse
 
nicolus profile image
Nicolas Bailly • Edited

Hey, thanks for your input !

You're probably right about that in the sense that SOP isn't a specification while CORS is, and the spec expects browsers to block cross origin requests by default.

However, the introduction to the spec says

User agents commonly apply same-origin restrictions to network requests. These restrictions prevent a client-side Web application running from one origin from obtaining data retrieved from another origin [...]
This specification extends this model in several ways

The way I interpret this is that historically browsers started to implement "Same Origin Policies" before CORS, and CORS was created primarily to allow requests that would never have been possible otherwise.

So while you're technically correct, I think I'll leave my imprecise wording because it personally helped me deal with CORS when I stopped thinking about it as "this thing that prevents me from querying my API" and started thinking of it as "this clever system that allows me to query my API even if it's on a different domain".