DevPrep
  • Interview Prep
  • Projects
  • Resources
  • Pricing
  • About Us
Submit Question
DevPrep
  • Pricing
  • About Us
Submit Question
← From Beginner to Expert in Fundamentals of Frontend
  • How the Web Works
  • Browsers: The Engines
  • Networking & Latency
  • HTTPS & TLS Handshake
  • CDNs & Edge Computing
  • WebSockets & WebRTC
  • RESTful Architecture
  • GraphQL Architecture
  • CORS (Cross-Origin Resource Sharing)
  • Load Balancing
  • Critical Rendering Path Deep Dive
  • DOM vs. CSSOM Construction
  • The Rendering Engine: Layout, Paint, Compositing
  • JavaScript Engine: V8 Internals
  • The Event Loop: Macro vs. Micro Tasks
  • Garbage Collection
  • Browser Storage Architecture
  • Service Workers & PWAs
  • Web Workers: Multi-Threading
← From Beginner to Expert in Fundamentals of Frontend

CORS (Cross-Origin Resource Sharing)

18 min read
CORSSame-Origin PolicyPre-flightOPTIONSAccess-Control HeadersCredentials

CORS: The Browser's Security Gatekeeper

CORS is not a bug — it's a security feature. It prevents malicious websites from making unauthorized requests to your API using a logged-in user's cookies.

The Same-Origin Policy

Two URLs have the same origin if they share the same protocol + domain + port:

  • https://app.com and https://app.com/api → Same origin
  • https://app.com and http://app.com → Different (protocol)
  • https://app.com and https://api.app.com → Different (subdomain)
  • https://app.com and https://app.com:8080 → Different (port)

How CORS Works

Simple Requests (No Pre-flight)

GET, HEAD, or POST with simple headers go directly. The browser adds an Origin header, and the server responds with Access-Control-Allow-Origin.

Pre-flight Requests

For "complex" requests (PUT, DELETE, custom headers, JSON content-type), the browser sends an OPTIONS request first:

  1. Browser sends OPTIONS with Access-Control-Request-Method and Access-Control-Request-Headers
  2. Server responds with allowed methods, headers, and max-age
  3. If approved, browser sends the actual request

Key Response Headers

HeaderPurposeExample
Access-Control-Allow-OriginWhich origins are allowedhttps://app.com or *
Access-Control-Allow-MethodsAllowed HTTP methodsGET, POST, PUT
Access-Control-Allow-HeadersAllowed request headersContent-Type, Authorization
Access-Control-Allow-CredentialsAllow cookies/authtrue
Access-Control-Max-AgeCache pre-flight result86400 (24 hours)

Common Gotcha: Credentials + Wildcard

You cannot use Access-Control-Allow-Origin: * with Access-Control-Allow-Credentials: true. You must specify the exact origin. This is a frequent source of bugs.

Practice

  • JavaScript
  • DSA
  • Machine Coding
  • System Design

Resources

  • Learning Tracks
  • Articles
  • Roadmaps
  • Compare Concepts
  • Glossary
  • Developer Tools
  • All Questions

Company

  • About
  • Pricing

Legal

  • Privacy Policy
  • Terms of Service
DevPrep

© 2026 DevPrep. All rights reserved.