A Short & Sweet Guide to Same-origin Policy & CORS

Published 2020-01-26

Rodent in front of mountains

Photo by Julia Solovey on Unsplash

This article covers same-origin policy and CORS from a web app point-of-view where your frontend is running on a different domain OR port than your backend and the only communication to your backend should be through your frontend. In other words, you don't have a publicly-facing API.

What is the same-origin policy?

The same-origin policy is a browser security feature that prevents a script from one domain to access resources on another domain.

What's considered same origin? If the protocol + host + port match, then the origins are the same.

Compared to https://example.com/...

URL same-origin?
https://exmaple.com/page1 true
http://exmaple.com/ false - different protocol
https://api.example.com/ false - different domain
https://example.com:4040/ false - different port

Why is the same-origin policy needed?

In short, to prevent scripts on random domains from hitting your server. Same-origin policy also protects against some CSRF vulnerabilities.

What is CORS?

Cross-Origin Resource Sharing, AKA CORS, is a way to give exceptions to the same-origin policy defined above. You can configure CORS on your server to allow requests from everywhere or just a select list of origins (like your frontend).

Simple or preflighted?

A CORS request can be either simple or preflighted. A CORS request is simple, and does not need to be preflighted if...

  • method is GET, HEAD, or POST
  • Content-Type is one of...

    • application/x-www-form-urlencoded
    • multipart/form-data
    • text-plain
  • Does not contain any custom headers, such as X-My-Customer-Header

If a request does not meet the requirements to be simple, then the browser must send a preflight request to the other domain to make sure the request is safe to send.

Request Headers

These headers are used in simple and preflight CORS requests.

Name What it does
Origin Where this request is coming from.
Access-Control-Request-Method Preflight - this tells the server what will actually be sent in actual request.
Access-Control-Request-Headers Preflight - same as Access-Control-Request-Method, except for the Headers.