Cos’è CORS? (Cross-Origin Resource Sharing)
Condivisione di Risorse tra Origini Diverse (W3C) — Architectural definition, operational mechanics, real-world examples, security posture, and client-side inspection utilities.
Web Protocols & Security Architecture Research
Cos’è 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.
Key Facts: Condivisione di Risorse tra Origini Diverse (W3C) (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.
How CORS Relates to Other Entities
CORS acts as a standardized, server-controlled exception mechanism to the browser default Same-Origin Policy.
The Access-Control-Allow-Origin HTTP response header dictates which requesting origins are permitted to read the response payload.
Browsers send an automated HTTP OPTIONS preflight request to verify server authorization before executing mutating methods (PUT, DELETE) or sending custom headers.
Client-side network requests initiated through window.fetch() or XMLHttpRequest are subject to browser CORS validation.
Why does CORS exist?
Nato per consentire alle moderne Single Page Application di interrogare API su domini o porte differenti in sicurezza.
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.
Nato per consentire alle moderne Single Page Application di interrogare API su domini o porte differenti in sicurezza.
How does CORS work?
Il browser verifica gli header Access-Control inviati dal server ed esegue una chiamata preflight OPTIONS se la richiesta è complessa.
Origin Check
Browser identifies that the target API origin differs from window.location (e.g. https://app.com vs https://api.com).
Preflight OPTIONS Dispatch
Browser sends HTTP OPTIONS probe containing `Origin`, `Access-Control-Request-Method`, and `Access-Control-Request-Headers`.
Server Validation
Server inspects Origin, checks against an approved allowlist, and returns `Access-Control-Allow-Origin: https://app.com`.
Actual Execution
Browser confirms headers match preflight approval, dispatches the real POST/PUT request, and delivers payload to JavaScript.
How is CORS implemented in code?
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.
Where is CORS commonly used?
React/Vue frontends on Vercel calling backend Go/Node APIs hosted on AWS.
Weather APIs, payment gateways, and font CDNs serving resources to arbitrary client websites.
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.
Can CORS introduce security vulnerabilities?
Insecure Wildcard with Credentials
Using `Access-Control-Allow-Origin: *` with `credentials: true` causes browsers to immediately fail, or reflecting arbitrary origins enables data theft.
Verify the incoming Origin against a strict whitelist before echoing it back with credentials.
What are common misconceptions about CORS?
CORS protects users from malicious frontend websites reading their authenticated data. Hackers using cURL or bots ignore CORS completely.
Frequently Asked Questions About CORS
Q:Why do I see a CORS error in my browser console but the request works in Postman?
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:
13. Related Comprehensive Guides
Ecosistema Tecnico Correlato e Passaggi Successivi
Domande Correlate
Why Does CORS Allow Simple GET Requests Without a Preflight?
Answer: CORS allows simple GET requests without preflight for backwards compatibility with legacy HTML form and image behaviors that predate CORS.
Why Do Browsers Send OPTIONS Preflight Requests?
Answer: Browsers send preflights to verify that older servers not expecting cross-origin calls explicitly permit the method and custom headers before execution.
Specifiche e Standard di Riferimento
Continua ad Imparare
CORS Policy & Preflight Handshake Lab
Simulate preflight OPTIONS probes and adjust Access-Control-Allow-* headers inside the browser sandbox.
References & Primary Sources
Every source below directly substantiates technical statements and protocol behaviors explained in Condivisione di Risorse tra Origini Diverse (W3C) (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]WHATWGPrimary SpecificationWHATWG Fetch • § 3.2 HTTP-network-fetchVerified Primary SourceTechnical 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]IETFPrimary SpecificationRFC 9110 • § 9.2.1Verified Primary SourceTechnical 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]OWASPAuthoritative Security StandardOWASP Cheat Sheet Series • Origin Validation & CredentialsVerified Primary SourceTechnical Claim Supported:
Documents the security risks of dynamic origin reflection without strict server-side allowlist verification (CORS misconfiguration vulnerabilities).
- [4]MDNDeveloper Authority (MDN)MDN Web Docs • CORS Preflight & Simple RequestsVerified Primary SourceTechnical Claim Supported:
Provides developer reference for simple requests vs. preflighted requests and safelisted headers (Accept, Accept-Language, Content-Language, Content-Type).