CORS, CSP & Same-Origin: Frontend Security Terminology Every Engineer Must Know

Jump to

The modern webpages are all about connectivity. Every website interacts with external services to make the webpage fast, powerful, and interactive, such as CDNs, analytics tools, and third-party apps. But that power brings big security challenges.

Edgescan’s 2024 Vulnerability Report shows that 19.1% of common web application vulnerabilities were due to XSS attacks, highlighting that these security threats are still very common. A small configuration mistake can leak sensitive data or allow attackers to inject malicious code into your pages.

Imagine if any random website could freely access your banking data, cookies, or personal info. That’s why browser security mechanisms were introduced to protect your data, allowing only trusted sites to share resources safely.

In this article, we deep dive into the concepts of Same-Origin Policy, Cross-Origin Resource Sharing, and Content Security Policy, how they work, their real-world use cases, and best practices to make your website safer and more secure.

What Is the Same-Origin Policy (SOP)

Same-origin policy (SOP) is a web security mechanism implemented by web browsers, aiming to prevent security vulnerabilities. Same-origin policy restricts the scripts loaded by one web page from accessing the content of another web page until they have the same origin.

Origin is the combination of three components:

  1. Schema (protocol)
  2. Domain name
  3. Port number

as shown in the image below.

Suppose your JavaScript file serves from this path: https://example.com/main.js

This means the script’s origin is example.com. Because of the same-origin policy (SOP), this can access any page from the same origin:

If any of these three components are different between two URLs, then they are considered as different origins:

  • https://example.com/blog
  • http://example.com/blog

Here, two different protocols are used in URLs, so they are considered to have different origins.

NOTE: HTTPS uses port 443 and HTTP uses port 80 by default.

What Is CORS (Cross-Origin Resource Sharing)

Cross-origin resource sharing (CORS) is a security protocol that allows or restricts requests from different domains for its resources. It is implemented on the server-side and tells the browser which external domains are allowed to access resources.

Suppose your website https://example1.com tries to fetch data from https://example2.com, then this is called a cross-origin request. By default, browsers block such requests because of the same-origin policy.

Let’s understand it with an example. When your web application tries to make a cross-origin request, instead of sending the request directly, the browser performs a security check by sending an HTTP OPTIONS request called a preflight request:

OPTIONS /data HTTP/1.1

Origin: https://example.com

Access-Control-Request-Method: POST

Access-Control-Request-Headers: Content-Type

If the server verifies that the request is safe, it responds with CORS headers:

HTTP/1.1 200 OK

Access-Control-Allow-Origin: https://frontend.com

Access-Control-Allow-Methods: GET, POST

Access-Control-Allow-Headers: Content-Type

After the preflight check is completed, the browser sends the real request to the server:

fetch("https://example/data", {

 method: "POST",

 headers: { "Content-Type": "application/json" },

 body: JSON.stringify({ name: "Test" })

})

.then(res => res.json())

.then(data => console.log(data));

What Is CSP (Content Security Policy)

Content Security Policy (CSP) is a security protocol that protects websites from various types of attacks, especially cross-site scripting (XSS), where attackers inject malicious scripts into webpages, or data injection attacks.

It consists of a set of instructions called directives that tell the browser which resources are allowed to be loaded on a webpage.

The content security policy is implemented by using an HTTP response header called Content-Security-Policy. This header contains a set of directives, and each directive describes different security policies:

Content-Security-Policy: default-src ‘self’; script-src ‘self’ <https://example.com>; object-src ‘none’;

In the above example, it has three directives:

  • default-src: Load resources only from the same origin as the webpage.
  • script-src: It allows scripts only from your own site and from https://example.com.
  • object-src: It restricts any plugins or external objects.

How SOP, CORS & CSP Work Together

Same-Origin Policy is a browser security mechanism that prevents resources from being accessed by third-party domains.

When the website https://example.com tries to integrate YouTube API services, which is hosted at https://www.googleapis.com/youtube. Here, SOP blocks the requests because the origins are not the same. To overcome this problem, CORS comes in.

When the browser tries to send cross-origin requests, it includes an origin header in the request. This request contains the domain name, protocol, and port of the website, which tells the server where the request is coming from.

If the server allows that request, it responds with a special CORS header: Access-Control-Allow-Origin: <https://example.com>

This tells the browser that the request is safe and can share data with this site.

If the request is simple, contains only GET, or POST method and doesn’t include any custom headers, and the server responds with Access-Control-Allow-Origin, everything works smoothly.

fetch("https://api.example.com/data")

 .then(res => res.json())

 .then(data => console.log(data));

But when a request uses custom headers, such as PUT and DELETE, or JSON payloads, the browser sends a preflight request first. This preflight request uses the Options method to validate the request.

fetch("<https://api.example.com/user/1>", {

 method: "DELETE",

 headers: { "Authorization": "Bearer token" }

});

The browser first sends a preflight request, which contains the origin and the Access-Control-Request-Methods:

OPTIONS /user/1 HTTP/1.1

Origin: <https://example.com>

Access-Control-Request-Method: DELETE

Access-Control-Request-Headers: Authorization

The server validates the request and agrees, then it sends a response which contains Access-Control-Allow-Origin and Access-Control-Allow-Methods:

Access-Control-Allow-Origin: <https://example.com>

Access-Control-Allow-Methods: GET, POST, DELETE

Access-Control-Allow-Headers: Authorization

After this browser sends an actual DELETE request.

Now come to CSP, it is another layer or security mechanism. While SOP and CORS data sharing and cross-origin, Content Security Policy focuses where content can load from.

It helps to prevent attacks such as Cross-Site Scripting (XSS), clickjacking, or data jacking.

Why These Policies Matter for Engineers

Building a modern web application is not just only writing code, it’s about keeping code safer and secure. Every request, API call, and third-party script can become a security risk if not properly managed.

Here’s why these policies matter:

  1. APIs and microservices run on different domains: In distributed systems, frontends and backends are usually hosted on separate domains. A misconfigured CORS policy, like using Access-Control-Allow-Origin, can leak private data to untrusted sites.
  2. Third-party integrations can introduce vulnerabilities: Services like analytics, ads, or CDNs load external content. Without a strict CSP, a single compromised script can inject malicious code and steal user data.
  3. Modern web apps rely heavily on APIs: Frameworks like React, Next.js, or Angular constantly fetch data from multiple origins. Poor understanding of SOP can cause blocked requests, app errors, or even data leaks.
  4. Misconfigurations have a real impact: A 2024 report by Invicti found that over 30% of tested web apps had insecure CORS setups that could expose sensitive data.
  5. They act as a security shield: SOP, CORS, and CSP together form a security layer that controls what data can be shared and how resources are loaded on a website.

Best Practices for Implementation

Ensuring robust security in web applications requires careful configuration of Same-Origin Policy, Cross-Origin Resource Sharing, and Content Security Policy.

Here are some best practices to enhance your app’s security:

  1. Keep SOP in mind when designing architecture: Design your application so that APIs and the frontend are on the same domain when possible. This minimizes the need for cross-origin requests and simplifies security configurations.
  2. Careful CORS Configuration: Never use Access-Control-Allow-Origin for sensitive data. Only allow trusted domains, and if your app needs cookies or authentication headers, set Access-Control-Allow-Credentials: true with a specific allowed origin.
  3. Implement a strong CSP: Start with a strict default-src ‘self’; policy to allow only same-origin resources, then carefully add trusted external sources as needed. Use report-uri or report-to to monitor violations and fix issues quickly.
  4. Regular Audit Security Headers: Use browser developer tools like Chrome DevTools and automated security scanners such as OWASP ZAP or Mozilla Observatory, to check that all security headers are correctly configured and to identify any misconfigurations or vulnerabilities.
  5. Test CORS Configurations: Regularly test your CORS setup using online tools such as Crosfix to ensure only the intended domains have access.

Conclusion

In this article, we discuss the Same-Origin policy and how it stops websites from reading data from other domains, but doesn’t stop requests from being sent. How Cross-Origin Resource Sharing solves this problem by letting servers specify which sites can access their resources using headers like Access-Control-Allow-Origin.

We also explore how Content Security Policy adds another layer of protection by controlling which content and scripts can load on a web page. How these policies together form a strong security layer for the modern web that helps developers build safer and more trusted applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

You may also like

Diagram showing TinyML running on microcontrollers with local AI inference for wearables, sensors, and IoT devices

What Is TinyML? An Introduction to Tiny Machine Learning

Artificial Intelligence has become an inseparable part of modern technology powering everything from recommendation engines to self-driving cars. But traditional AI models are often large, computationally expensive, and dependent on

Diagram showing FOIT, FOUT, and font-display strategies in web typography

Optimizing Fonts: FOIT vs FOUT vs Font Display Strategies

Introduction Fonts play a crucial role in web design. A beautiful typeface enhances readability, aesthetics, and brand perception but when fonts aren’t optimized, they can become one of the biggest

Categories
Interested in working with Frontend ?

These roles are hiring now.

Loading jobs...
Scroll to Top