Understand Web Security: SOP (Same-Origin Policy) and CORS (Cross-Origin Resource Sharing)
SOP (Same-Origin Policy) and CORS (Cross-Origin Resource Sharing) in depth!
SOP (Same-Origin Policy) and CORS (Cross-Origin Resource Sharing) are essential for keeping your web applications safe. They prevent unauthorized access to your data, protecting it from potential attacks like XSS and CSRF.
Configure them properly to keep hackers at bay!
Ignoring SOP and CORS can break your app and expose it to serious risks like XSS or CSRF attacks. A solid understanding helps you protect your app and avoid those frustrating “blocked by CORS policy” errors.
Same-Origin Policy (SOP)
SOP (Same-Origin Policy) ensures scripts running on one website can’t access data from another website unless explicitly permitted
What is Same-Origin Policy (SOP)?
It’s a browser-enforced security feature that you don’t need to implement — it’s built-in. Your job is to work within its rules and configure exceptions using CORS (Cross-Origin Resource Sharing) when needed.
What is an Origin?
An origin is defined by three key parts:
Protocol (e.g.,
http
,https
)Domain (e.g.,
example.com
)Port (e.g.,
:80
)
For example:
https://example.com:80 and http://example.com:80 are different origins due to the protocol.
https://example.com:80 and https://example.com:8080 are different origins due to the port.
How SOP Works
SOP blocks scripts or resources on one origin from accessing data on another unless the protocol, domain, and port all match exactly.
For instance:
If a script on https://example.com tries to access https://another-site.com , SOP will block it because the origins don’t match. This protects users from malicious sites stealing sensitive data, like personal information or cookies.
What Happens When Your App Needs Data from Another Origin?
If your app needs to fetch data from a different domain (like an API), the browser blocks it by default for safety.
To allow this, the API must send CORS headers in its response, granting your app permission to access the data.
CORS essentially provides a way to safely configure exceptions to SOP when cross-origin access is needed.
CORS (Cross-Origin Resource Sharing) is a system that uses HTTP headers to decide if browsers should allow or block frontend JavaScript code from accessing data from different origins (websites).
CORS is like a permission system that lets websites share resources across websites.
How CORS (Cross-Origin Resource Sharing) Works
CORS is a security feature built into browsers to control how one website can access resources from another. Here’s a clearer explanation for junior developers:
Keep reading with a 7-day free trial
Subscribe to Front-end World to keep reading this post and get 7 days of free access to the full post archives.