1. What is the Same-Origin Policy?
The Same-Origin Policy (SOP) is a critical browser security boundary designed to isolate potentially malicious documents. Under SOP, JavaScript running on https://bank.com cannot read cookies, local storage, or Fetch responses from https://malicious.com.
Two URLs have the same origin if and only if their Protocol (Scheme), Host (Domain), and Port are identical:
https://api.example.com:443 vs https://example.com:443 → CROSS-ORIGIN (Subdomain mismatch)http://example.com:80 vs https://example.com:443 → CROSS-ORIGIN (Protocol mismatch)https://example.com/app vs https://example.com/api → SAME-ORIGIN (Path differences allowed)2. How CORS Enables Secure Cross-Origin Access
Cross-Origin Resource Sharing (CORS) allows web servers to explicitly declare which foreign origins have permission to read their data by sending HTTP response headers:
- Access-Control-Allow-Origin: Specifies allowed requesting origins (e.g.
https://app.curious-techie.com). - Access-Control-Allow-Methods: Permitted HTTP methods (e.g.
GET, POST, PUT, DELETE). - Access-Control-Allow-Headers: Allowed request headers (e.g.
Content-Type, Authorization). - Access-Control-Max-Age: How long (in seconds) the browser can cache preflight OPTIONS responses.
3. Preflight OPTIONS Requests & Caching
For non-simple requests (such as sending JSON payloads with Content-Type: application/json or custom Authorization: Bearer headers), the browser automatically dispatches an HTTP OPTIONS preflight request before sending the actual payload.
4. The Credentials & Wildcard Pitfall
A common security pitfall occurs when attempting to share authenticated sessions across origins:
Browsers strictly refuse to expose responses if wildcard * is used with credentials enabled. The server must echo back the specific, validated requesting Origin header instead.