🟡 MediumBrowser APIs📖 Theory Question

What is the Same-Origin Policy and how does CORS work?

💡

Hint

Browser blocks cross-origin requests by default; server opts in via CORS headers

Full Answer

The Same-Origin Policy (SOP) blocks web pages from reading resources from a different origin (protocol + domain + port combination).

// Same origin — all identical: protocol, domain, port
// https://app.com/page can read from https://app.com/api ✅
// https://app.com/page CANNOT read from https://api.other.com ❌

// CORS (Cross-Origin Resource Sharing):
// Server opts in by sending response headers

// Server response headers to allow access:
Access-Control-Allow-Origin: https://app.com  // or * for all
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true // if sending cookies

// Simple requests (GET, POST with basic headers) — no preflight
fetch('https://api.other.com/data');

// Preflighted requests — browser sends OPTIONS first
fetch('https://api.other.com/data', {
  method: 'DELETE',           // non-simple method
  headers: { 'X-Custom': '1' } // non-simple header
});
// Browser sends: OPTIONS https://api.other.com/data
// → checks server allows it before actual request

// CORS does NOT apply to:
// - Server-to-server (Node.js fetch, cURL)
// - <img>, <script>, <link> tags (but limited access)
// - Same origin
💡 CORS is enforced by the BROWSER only — it's not a server-side security measure. Server-to-server calls bypass it entirely. The browser is protecting users from malicious scripts, not the server from requests.

More Browser APIs Questions

🟢 EasyWhat is the Fetch API and how do you handle errors correctly?🟢 EasyWhat is the difference between localStorage, sessionStorage, and cookies?🟡 MediumWhat are Web Workers and when should you use them?🟡 MediumWhat are Service Workers and what problems do they solve?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint