Web Fundamentals

CORS Explained: Cross-Origin Resource Sharing

mediumWeb Fundamentals

CORS Explained: Cross-Origin Resource Sharing

Learn the interview-ready mental model, practical trade-offs, and production patterns for this web fundamentals topic.

Topic content

TL;DRCORS is a browser security feature that controls cross-origin requests. Configure Access-Control-Allow-Origin and handle preflight OPTIONS requests.
High Signal
Google
Meta
Netflix
Agoda
Atlassian
30-Second Answerstart every interview with this

Cross-Origin Resource Sharing (CORS) is a browser security mechanism that restricts cross-origin HTTP requests. It prevents malicious sites from reading sensitive data from other origins. Proper configuration on the server side (headers) is required for legitimate cross-origin communication.

The browser is the club owner. When a request comes from a different origin (another club), the bouncer (CORS policy) checks the guest list (headers). If the origin is not allowed, the request is blocked before it reaches the server.

Cross-origin request from frontend
Browser checks CORS headers from server
Allowed → Request proceeds
Blocked → CORS error in console

1Simple vs Preflight Requests

Simple requests (GET, HEAD, POST with basic headers) are sent directly. Non-simple requests (PUT, DELETE, custom headers) trigger a preflight OPTIONS request first.

Simple Request

Browser sends actual request → Server responds with CORS headers

Preflight

Browser sends OPTIONS → Server responds with Allow headers → Browser sends actual request

2Essential CORS Headers

Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Access-Control-Allow-Credentials, and Access-Control-Max-Age.

3Server-Side Implementation

Configure CORS middleware or manually set headers. Always specify exact origins in production instead of using wildcard (*).

Key Takeaways
  • CORS is a browser-enforced security policy
  • Simple requests don't need preflight; others do
  • Always specify exact origins in production
  • Handle OPTIONS requests for preflight
  • Use middleware like cors() in Express
  • Credentials require specific origin + Allow-Credentials header
  • Test cross-origin requests thoroughly