DEV Community

Lali Micskei
Lali Micskei

Posted on • Edited on

Understanding CORS: 1. What is it?

If you’ve struggled to understand CORS, you’re not alone! Many new developers find it confusing at first. Here’s a step-by-step breakdown to help you grasp the basics of CORS and browser security:

1. Browsers and Security Features
When we browse the internet, we often overlook how much we rely on browsers and their built-in security features. All modern browsers implement these protections to keep users safe.

2. Same-Origin Policy (SOP)
One of the core browser security features is the Same-Origin Policy (SOP). This policy ensures that scripts running on one website cannot access data from another website if the origin (protocol, domain, and port) is different. Without SOP, a malicious web page could read sensitive data from other sites you’re logged into, because browsers automatically send your credentials (like cookies) with requests.

For example, if you visit a page containing malicious code, and that code tries to send a request to a service where you’re logged in, your data remains safe. The browser will block the malicious script from reading the response, thanks to the Same-Origin Policy.

4. Why CORS Exists
Sometimes, legitimate sites need to communicate and read responses from other domains (cross-origin requests). In these cases, the server you’re trying to access must explicitly allow your browser to read its responses. This permission is granted via special HTTP headers called CORS (Cross-Origin Resource Sharing) headers. Only if the server includes the appropriate CORS headers will the browser allow your site to access the response data.

By understanding these steps—how browsers protect you by default, what the Same-Origin Policy does, and how CORS allows controlled exceptions—you’ll have a much clearer picture of how web security and cross-origin requests work.

Top comments (0)