| |

Web Security 02 🛡️ Same-Origin Policy & CORS — Understanding browser origin isolation, preflight requests, and safe CORS configurations

⏱️ Estimated read: 10 min | |

The Same-Origin Policy (SOP) is the bedrock of the browser’s security model. It is a restrictive sandbox mechanism that prevents a script loaded from one origin from interacting with resources or data from another origin. In an era where users maintain long-lived sessions with multiple high-value services—such as banking, email, and cloud storage—SOP ensures that a malicious site opened in one tab cannot “reach over” and steal session cookies or read private data from another tab.

While SOP provides essential isolation, the modern web requires controlled collaboration between different domains. Cross-Origin Resource Sharing (CORS) was developed as the standardized exception to SOP, allowing servers to explicitly declare which origins are permitted to bypass the default isolation. CORS is not a tool to “disable” security; rather, it is a protocol that allows a server to relax the browser’s restrictions for specific, trusted clients. Understanding the interplay between these two mechanisms is vital for building secure APIs that remain accessible to legitimate frontend applications.

This chapter explores the components of a web origin, the mechanics of how browsers enforce isolation, and the complex handshake of CORS preflight requests. The sections that follow cover origin definition logic, the differentiation between simple and preflighted requests, and the implementation of secure, production-ready CORS policies.

Key point: The Same-Origin Policy (SOP) blocks scripts from reading data across different origins by default, while CORS acts as a server-side opt-in mechanism that allows browsers to selectively bypass these restrictions for trusted domains.


Why X exists

The malicious script problem. Without origin isolation, any website you visit could execute JavaScript to read the content of other open tabs. A simple “funny cat video” site could silently scan your open banking tab, extract your balance, and transmit it to a remote server. SOP exists to ensure that code can only access data within its own security boundary.

The ambient authority problem. Browsers automatically attach “ambient” credentials—such as cookies and HTTP authentication headers—to outgoing requests. If a malicious site triggers a background request to your email provider, the browser would include your login session cookie. SOP prevents the malicious site from reading the sensitive response that results from that authenticated request.

The legacy infrastructure problem. Many internal enterprise servers were built before modern web security standards existed. These servers often assume that if a request contains a valid session cookie, it must be legitimate. Preflight requests exist to “ask permission” before sending complex or potentially destructive data to these older systems that might not understand CORS.

The modern API ecosystem problem. Modern web apps are rarely monolithic; they often consume data from multiple domains (CDNs, identity providers, and specialized microservices). CORS exists to provide a standardized, cryptographically-independent way for these disparate services to interact securely without breaking the foundational sandbox of the browser.

The CSRF mitigation problem. While SOP doesn’t prevent a site from sending a request to another origin (a behavior exploited in Cross-Site Request Forgery), it does prevent the site from reading the response. This fundamental wall ensures that even if a request is successfully forged, the sensitive data remains shielded behind the browser’s isolation layer.


a. Defining the Origin: Scheme, Host, and Port

A web “Origin” is defined by the unique combination of three specific components: the Protocol (Scheme), the Hostname, and the Port. If any one of these three elements differs between two URLs, the browser considers them to be distinct origins.

// Example: Comparing Origins to https://api.example.com:443

// SAME ORIGIN:
// https://api.example.com/v1/users (Path changes are allowed)

// CROSS ORIGIN:
// http://api.example.com (Protocol mismatch: HTTP vs HTTPS)
// https://beta.api.example.com (Host mismatch: Subdomains are different)
// https://api.example.com:8080 (Port mismatch: 443 vs 8080)

The Same-Origin Policy applies strictly to data access. While a site is generally permitted to embed resources from other origins (such as <img>, <script>, or <iframe> tags), it is strictly forbidden from reading the contents of those resources via JavaScript. For instance, you can display an image from another site, but you cannot use a canvas element to read the pixel data of that image unless the remote server explicitly permits it via CORS.

This isolation extends to the Document Object Model (DOM). JavaScript on origin-a.com cannot access the window or document objects of a frame or tab running origin-b.com. This prevents “clickjacking” and data extraction attacks where a malicious site attempts to wrap a legitimate site in an invisible iframe to intercept user input.


b. The CORS Handshake: Simple vs. Preflight Requests

When a script attempts a cross-origin request (e.g., via fetch() or XMLHttpRequest), the browser first categorizes the request. Simple Requests are those that use standard methods (GET, POST, HEAD) and a restricted set of safe headers. These are sent directly to the server, and the browser checks the response for the Access-Control-Allow-Origin header after the fact.

# A Simple Request (sent immediately)
GET /data HTTP/1.1
Host: api.example.com
Origin: https://myapp.com

If the request is Non-Simple—meaning it uses methods like PUT or DELETE, or includes custom headers (like Authorization or Content-Type: application/json)—the browser initiates a Preflight Request. This is an OPTIONS request sent to the server to verify that the cross-origin interaction is safe to perform.

# The Preflight (OPTIONS)
OPTIONS /data HTTP/1.1
Access-Control-Request-Method: DELETE
Access-Control-Request-Headers: X-Custom-Header
Origin: https://myapp.com

The server must respond to this OPTIONS request with the appropriate Access-Control-Allow-* headers. Only if the preflight is successful will the browser send the actual, intended request. This “check-before-act” mechanism protects servers from receiving unexpected data or methods that they were not designed to handle from untrusted origins.


c. Safe CORS Configuration and Credentials

The most critical header in a CORS policy is Access-Control-Allow-Origin. While using a wildcard (*) is common in development, it is dangerous for APIs that handle private data. In production, servers should dynamically reflect the Origin header from the request against an allow-list of trusted domains.

// Server-side logic for dynamic origin reflection
const allowedOrigins = ['https://app.example.com', 'https://admin.example.com'];
const origin = request.headers.origin;

if (allowedOrigins.includes(origin)) {
  response.setHeader('Access-Control-Allow-Origin', origin);
  response.setHeader('Vary', 'Origin'); // Ensure caches don't mix origins
}

Handling Credentials (cookies, HTTP auth) adds another layer of complexity. If a frontend needs to send or receive cookies across origins, the request must set withCredentials: true and the server must respond with Access-Control-Allow-Credentials: true. Crucially, when credentials are involved, the Access-Control-Allow-Origin header cannot be a wildcard; it must specify a single, explicit origin.

Security professionals also use the Vary: Origin header to ensure that intermediate caches (like CDNs or proxies) do not serve a cached CORS response intended for origin-a.com to a user visiting from origin-b.com. This prevents “CORS cache poisoning” where a restrictive policy is cached and subsequently blocks legitimate traffic from other permitted origins.


Complete Example Session

// ============================================
// PART 1: THE FRONTEND REQUEST (with JSON)
// ============================================
// This is a "Non-Simple" request due to JSON content-type
fetch('https://api.example.com/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Alice' })
});

// ============================================
// PART 2: BROWSER AUTOMATIC PREFLIGHT
// ============================================
// OPTIONS /users HTTP/1.1
// Origin: https://myfrontend.com
// Access-Control-Request-Method: POST
// Access-Control-Request-Headers: content-type

// ============================================
// PART 3: SERVER HANDLING THE PREFLIGHT (Node/Express)
// ============================================
app.options('/users', (req, res) => {
  const origin = req.headers.origin;
  if (allowedOrigins.includes(origin)) {
    res.header('Access-Control-Allow-Origin', origin);
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    res.header('Access-Control-Max-Age', '86400'); // Cache preflight for 24h
    res.sendStatus(204); // No Content
  } else {
    res.sendStatus(403); // Forbidden
  }
});

// ============================================
// PART 4: THE ACTUAL POST REQUEST (If Preflight Passed)
// ============================================
// POST /users HTTP/1.1
// Origin: https://myfrontend.com
// Content-Type: application/json

// ============================================
// PART 5: SERVER RESPONSE WITH CORS HEADERS
// ============================================
// HTTP/1.1 201 Created
// Access-Control-Allow-Origin: https://myfrontend.com
// Vary: Origin

// ============================================
// PART 6: HANDLING CREDENTIALS (FRONTEND)
// ============================================
fetch('https://api.example.com/profile', {
  credentials: 'include' // Send cookies
});

// ============================================
// PART 7: SERVER ALLOWING CREDENTIALS
// ============================================
// Access-Control-Allow-Origin: https://myfrontend.com (Must be explicit)
// Access-Control-Allow-Credentials: true

// ============================================
// PART 8: BLOCKING MALICIOUS ORIGIN
// ============================================
// If Origin: https://evil-site.com
// Server responds WITHOUT Access-Control-Allow-Origin
// Browser blocks the JS from reading the response body.

// ============================================
// PART 9: EXPOSING CUSTOM HEADERS
// ============================================
// By default, JS can't read custom headers like X-Request-ID
res.header('Access-Control-Expose-Headers', 'X-Request-ID');

// ============================================
// PART 10: RESULT
// ============================================
// The browser allows the frontend script to process the user data.

The parts above cover the transition from a non-simple request trigger, the preflight negotiation, dynamic origin reflection, credential handling, and header exposure.


Quick Reference

Components of an Origin

ComponentExampleNote
Protocolhttps://Must match exactly
Hostnameapi.example.comSubdomains count as different hosts
Port:443Optional in URL, but checked by SOP

Critical CORS Headers

HeaderTypePurpose
OriginRequestInjected by browser; indicates source
Access-Control-Allow-OriginResponseDefines permitted origins
Access-Control-Allow-MethodsResponseDefines permitted HTTP verbs
Access-Control-Allow-HeadersResponseDefines permitted custom headers
Access-Control-Allow-CredentialsResponsePermits cross-origin cookie usage

Simple Request Criteria (No Preflight)

PropertyAllowed Values
MethodGET, POST, HEAD
Content-Typetext/plain, multipart/form-data, application/x-www-form-urlencoded
HeadersAccept, Accept-Language, Content-Language, Content-Type (subset)

Best Practices

✅ Do This:

// Validate against a whitelist of origins
const whitelist = ['https://a.com', 'https://b.com'];          // ✅

// Always include Vary: Origin for dynamic responses
res.header('Vary', 'Origin');                                  // ✅

// Set a reasonable Max-Age for preflight caching
res.header('Access-Control-Max-Age', '3600');                  // ✅

// Use explicit origins when using credentials
res.header('Access-Control-Allow-Origin', 'https://trusted.com'); // ✅

❌ Don’t Do This:

// Use wildcard for authenticated APIs
res.header('Access-Control-Allow-Origin', '*');                // ❌

// Reflection of any Origin without validation
res.header('Access-Control-Allow-Origin', req.headers.origin); // ❌

// Allow all headers or methods blindly
res.header('Access-Control-Allow-Headers', '*');               // ❌

// Forget to handle the OPTIONS method separately
// (Leading to 404 or 405 errors on preflights)               // ❌

Common Pitfalls

PitfallWhy It HappensFix
Preflight FailureOPTIONS method returns 404/405Implement an OPTIONS route on the server
Credential ErrorWildcard used with Credentials: trueProvide an explicit origin in the header
Cache CollisionMissing Vary: Origin headerAdd Vary: Origin to all CORS responses
Missing Custom HeadersHeaders not listed in Expose-HeadersUse Access-Control-Expose-Headers
Localhost mismatchlocalhost vs 127.0.0.1Treat them as separate origins in whitelist
Protocol MismatchMixed HTTP and HTTPSEnforce HTTPS everywhere via HSTS

Real-World Examples

1. Checking Origin Identity

const origin = window.location.origin; // e.g. "https://myapp.com"

2. Simple GET with CORS

Access-Control-Allow-Origin: * (Public API)

3. Standard JSON API Preflight

Access-Control-Allow-Headers: Content-Type, Authorization

4. Handling Port-specific Origin

if (req.headers.origin === 'http://localhost:3000') { ... }

5. Exposing Pagination Headers

Access-Control-Expose-Headers: X-Total-Count, Link

6. Express.js CORS Middleware

app.use(cors({ origin: 'https://example.com' }));

7. Setting Preflight Cache

Access-Control-Max-Age: 600

8. Allowing Multiple Methods

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

9. Credentials Opt-in (Client)

axios.get(url, { withCredentials: true });

10. Varying by Origin (Nginx)

add_header Vary Origin;

Visual

The SOP Block

┌──────────────────────────────────────────────┐
│  BROWSER SANDBOX                             │
│                                              │
│  TAB 1: site-a.com                           │
│    Script attempts:                          │
│    fetch('https://site-b.com/api') ──┐        │
│                                      │        │
│  TAB 2: site-b.com                   │        │
│    [ Private Cookies ]               │        │
│    [ Session Data ]                  │        │
│                                      │        │
│  SOP Enforcement:                    │        │
│    Request goes out  ───────────►    │        │
│    Response returns  ───────────►    │        │
│    READ ACCESS       ◄─────────── X  │        │
│    (Permission Denied)                        │
└──────────────────────────────────────────────┘

Simple Request Flow

┌─────────────┐       ┌──────────────┐       ┌─────────────┐
│   BROWSER   │       │    NETWORK   │       │    SERVER   │
└──────┬──────┘       └──────┬───────┘       └──────┬──────┘
       │    HTTP GET (Origin: A)     │              │
       │────────────────────────────►│              │
       │                             │              │
       │    HTTP 200 (ACAO: A)       │              │
       │◄────────────────────────────│              │
       │                             │              │
       │    (Check ACAO Matches)     │              │
       │    (JS reads response)      │              │

Preflight Handshake Flow

┌─────────────┐       ┌──────────────┐       ┌─────────────┐
│   BROWSER   │       │    NETWORK   │       │    SERVER   │
└──────┬──────┘       └──────┬───────┘       └──────┬──────┘
       │   OPTIONS (Preflight)       │              │
       │────────────────────────────►│              │
       │                             │              │
       │   HTTP 204 (Allow: POST)    │              │
       │◄────────────────────────────│              │
       │                             │              │
       │   ACTUAL POST REQUEST       │              │
       │────────────────────────────►│              │

Summary

ItemValue
PolicySame-Origin Policy (SOP)
Opt-outCross-Origin Resource Sharing (CORS)
OriginScheme + Host + Port
Preflight MethodHTTP OPTIONS
Success HeaderAccess-Control-Allow-Origin
Security ModeRestrictive by default
ConflictWildcard (*) vs Credentials (true)

Key takeaways:

  • Origin is a rigid triple. A change in protocol, host, or port creates a new origin that triggers Same-Origin Policy restrictions.
  • SOP protects data, not actions. Scripts can generally send data cross-origin (CSRF), but they cannot read the response without server permission.
  • CORS is a handshake, not a firewall. CORS resides in the browser. If a non-browser client (like cURL or Postman) makes a request, CORS headers are ignored.
  • Preflights protect legacy state. The OPTIONS preflight ensures the server is aware of modern cross-origin standards before sending complex payloads.
  • Whitelisting is mandatory for security. Never mirror the Origin header without validating it against a trusted list of domains.
  • Credentials require explicit origins. If you use cookies across domains, you cannot use the * wildcard in your CORS configuration.

Remember: The Same-Origin Policy is your user’s primary defense against cross-site data theft. CORS provides a controlled, secure bridge through that defense, but it must be configured with explicit white-lists and appropriate headers to ensure that security is not traded for interoperability.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!