100% Clientseitige Berechnung • Keine Server-Logs • Sofortige Ausführung
Curious TechieEntwickler-Toolbox
Web Security & DefensesW3C / WHATWG Fetch Living Standard6 min ReadDirect Definition • Curious-Techie

Was ist CORS? (Cross-Origin Resource Sharing)

Cross-Origin Resource Sharing (W3C-Standard) — Architectural definition, operational mechanics, real-world examples, security posture, and client-side inspection utilities.

CT
Curious-Techie Engineering TeamVerifizierter Autor

Web Protocols & Security Architecture Research

Veröffentlicht:
•
Aktualisiert:
•6 min
Maßgebliche Spezifikation:WHATWG Fetch Living Standard(WHATWG)
Geprüft von Curious-Techie Architecture Peer Review Group
Primary Question • Immediate Technical Answer

Was ist CORS? (Cross-Origin Resource Sharing)

Supporting Architectural Explanation

By default, the browser’s fundamental security baseline—the Same-Origin Policy (SOP)—prevents JavaScript running on one website (e.g. app.com) from reading response payloads fetched from a different origin (e.g. api.com). CORS acts as a controlled relaxation of this policy.

When cross-origin requests involve non-standard methods (PUT, DELETE) or custom headers (Authorization), the browser automatically dispatches an `OPTIONS` preflight request. If the server responds with matching `Access-Control-Allow-Origin` and related headers, the browser delivers the data to frontend code; otherwise, it drops the response and throws a CORS error.

#
Answer-Ready Section • Standalone Statements

Key Facts: Cross-Origin Resource Sharing (W3C-Standard) (CORS)

  • CORS is enforced exclusively by client web browsers, not by server firewalls, command-line utilities, or backend scripts.
  • A web origin consists strictly of three components: URI Scheme (protocol), Host (domain name or IP), and Port number.
  • Two URLs are cross-origin if scheme, host, or port differ, even if they share the exact same top-level domain.
  • Non-simple HTTP requests trigger an automatic preflight HTTP OPTIONS probe before the browser transmits the actual payload.
  • The Fetch Standard explicitly forbids the wildcard Access-Control-Allow-Origin: * when Access-Control-Allow-Credentials: true is set.
  • CORS does not prevent an HTTP request from hitting an API server; CORS prevents the web browser from releasing the response body to untrusted JavaScript.
Factual statements formulated to be self-contained and independently verifiable.
Contextual Graph • Semantic Connections

How CORS Relates to Other Entities

Cross-Origin Resource Sharing (CORS)→ relaxes →Same-Origin Policy (SOP)

CORS acts as a standardized, server-controlled exception mechanism to the browser default Same-Origin Policy.

Cross-Origin Resource Sharing (CORS)→ specifies →Access-Control-Allow-Origin

The Access-Control-Allow-Origin HTTP response header dictates which requesting origins are permitted to read the response payload.

Cross-Origin Resource Sharing (CORS)→ depends on →HTTP OPTIONS Preflight Request

Browsers send an automated HTTP OPTIONS preflight request to verify server authorization before executing mutating methods (PUT, DELETE) or sending custom headers.

Cross-Origin Resource Sharing (CORS)→ governs →Fetch API & XMLHttpRequest

Client-side network requests initiated through window.fetch() or XMLHttpRequest are subject to browser CORS validation.

Secondary Question • Origins & Motivation

Why does CORS exist?

Direkte Antwort (AEO-Zusammenfassung):

Ermöglicht den gezielten Datenaustausch zwischen unterschiedlichen Domains, ohne die grundlegende Same-Origin Policy aufzugeben.

Historical Context & Genesis

Before CORS, web browsers strictly blocked all cross-origin AJAX requests to protect users from malicious sites reading private intranet or bank data. However, the rise of decoupled JAMstack frontends and independent microservice API gateways required a secure way to share data across subdomains and domains.

Core Architectural Problem Solved

Ermöglicht den gezielten Datenaustausch zwischen unterschiedlichen Domains, ohne die grundlegende Same-Origin Policy aufzugeben.

Secondary Question • Architecture & Flow

How does CORS work?

Direct Answer:

Der Browser prüft serverseitige Access-Control-Header und schützt empfindliche APIs vor unberechtigten Web-Clients.

1

Origin Check

Browser identifies that the target API origin differs from window.location (e.g. https://app.com vs https://api.com).

2

Preflight OPTIONS Dispatch

Browser sends HTTP OPTIONS probe containing `Origin`, `Access-Control-Request-Method`, and `Access-Control-Request-Headers`.

3

Server Validation

Server inspects Origin, checks against an approved allowlist, and returns `Access-Control-Allow-Origin: https://app.com`.

4

Actual Execution

Browser confirms headers match preflight approval, dispatches the real POST/PUT request, and delivers payload to JavaScript.

Technical Examples • Implementation

How is CORS implemented in code?

Production CORS Configuration in Express.jsjavascript
import cors from 'cors';
import express from 'express';
const app = express();

const allowedOrigins = [
  'https://curious-techie.com',
  'https://app.curious-techie.com'
];

app.use(cors({
  origin: (origin, callback) => {
    // Allow requests with no origin (like mobile apps or cURL)
    if (!origin || allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error('Blocked by CORS'));
    }
  },
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true, // Allow cookies
  maxAge: 86400      // Cache preflight for 24 hours
}));

Architectural Explanation: Validates Origin dynamically against an allowlist, allowing credentialed calls without using unsafe wildcards.

Production Context • System Architecture

Where is CORS commonly used?

Decoupled Web Apps & Single Page Applications (SPAs)

React/Vue frontends on Vercel calling backend Go/Node APIs hosted on AWS.

Public Third-Party APIs & SaaS

Weather APIs, payment gateways, and font CDNs serving resources to arbitrary client websites.

Architectural Trade-Offs • Pros & Cons

What are the advantages and limitations of CORS?

Core Advantages

Fine-Grained Access Control

API servers explicitly dictate exactly which origins, methods, and headers are authorized.

Preflight Caching

`Access-Control-Max-Age` allows browsers to cache preflight approvals, eliminating roundtrips on repeated calls.

Architectural Limitations

Browser-Only Enforcement

CORS is strictly enforced by browsers; backend tools like cURL, Postman, and Python scripts bypass CORS entirely.

Risk Analysis • Attack Vectors

Can CORS introduce security vulnerabilities?

Threat Vector

Insecure Wildcard with Credentials

Using `Access-Control-Allow-Origin: *` with `credentials: true` causes browsers to immediately fail, or reflecting arbitrary origins enables data theft.

Recommended Mitigation:

Verify the incoming Origin against a strict whitelist before echoing it back with credentials.

Myths vs Reality • Technical Clarification

What are common misconceptions about CORS?

Myth / Fallacy
"CORS is a security firewall that protects backend servers from being hacked."
Technical Reality

CORS protects users from malicious frontend websites reading their authenticated data. Hackers using cURL or bots ignore CORS completely.

Secondary Questions • Direct Technical Answers

Frequently Asked Questions About CORS

Q:Why do I see a CORS error in my browser console but the request works in Postman?

Direkte Antwort (AEO-Zusammenfassung):Because CORS is a browser security mechanism designed to stop malicious websites from using your session cookies to read private APIs. Postman is not a browser executing untrusted third-party code, so it does not enforce CORS.

In fact, the server often successfully executes the request and returns 200 OK, but the browser blocks JavaScript from seeing the response because CORS headers were missing.

12. Related Interactive Tools

Inspect, test, and verify this protocol directly in your browser with 100% private client-side execution:

Companion Interactive Tool100% Client-Side Execution

Test & Verify with CORS Checker & Builder

Validate and generate secure Cross-Origin Resource Sharing (CORS) headers.

Companion Interactive Tool100% Client-Side Execution

Test & Verify with HTTP Header Analyzer

Analyze raw or live HTTP response headers for caching and architecture.

Companion Interactive Tool100% Client-Side Execution

Test & Verify with Security Headers Checker

Audit HSTS, CSP, X-Frame-Options, and OWASP recommended web headers.

Authoritative Sourcing & Verification

References & Primary Sources

Every source below directly substantiates technical statements and protocol behaviors explained in Cross-Origin Resource Sharing (W3C-Standard) (CORS). Curious-Techie prioritizes official Internet standards (IETF RFCs, W3C Recommendations, WHATWG specifications) and established security bodies (OWASP, NIST). Zero sponsored or secondary links.

  1. [1]WHATWGPrimary SpecificationWHATWG Fetch • § 3.2 HTTP-network-fetch
    Verified Primary Source
    Technical Claim Supported:

    Defines the normative browser CORS protocol, preflight cache validation (Access-Control-Max-Age), and the prohibition of wildcard Access-Control-Allow-Origin: * when Access-Control-Allow-Credentials is true.

    “For a CORS request with credentials, the server cannot specify a wildcard for Access-Control-Allow-Origin. It must specify an explicit origin.”
  2. [2]IETFPrimary SpecificationRFC 9110 • § 9.2.1
    Verified Primary Source
    Technical Claim Supported:

    Specifies that the Origin request header indicates the scheme, host, and port of the originating context and must not be altered by user-agent JavaScript.

  3. [3]OWASPAuthoritative Security StandardOWASP Cheat Sheet Series • Origin Validation & Credentials
    Verified Primary Source
    Technical Claim Supported:

    Documents the security risks of dynamic origin reflection without strict server-side allowlist verification (CORS misconfiguration vulnerabilities).

  4. [4]MDNDeveloper Authority (MDN)MDN Web Docs • CORS Preflight & Simple Requests
    Verified Primary Source
    Technical Claim Supported:

    Provides developer reference for simple requests vs. preflighted requests and safelisted headers (Accept, Accept-Language, Content-Language, Content-Type).