JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsjavascript
PrevNext

Learn the concept

CORS

javascript
senior
cors

What is CORS, when do CORS errors occur, and how can they be resolved?

cors
fetch
http
security
browser
same-origin-policy
preflight
Quick Answer

CORS (Cross-Origin Resource Sharing) is a browser security mechanism that blocks cross-origin requests unless the server explicitly allows them via HTTP headers like Access-Control-Allow-Origin.

Detailed Explanation

What is CORS?

  • HTTP-header based mechanism for cross-origin requests
  • Browsers enforce same-origin policy by default
  • Server must explicitly allow cross-origin access

What Triggers CORS?

  • Requests to different origin (protocol + domain + port)
  • Applies to: fetch(), XMLHttpRequest, Web Fonts, WebGL textures

Simple vs Preflighted Requests:

Simple Requests (no preflight):

  • Methods: GET, HEAD, POST
  • Standard headers only (Accept, Content-Language, Content-Type)
  • Content-Type: text/plain, multipart/form-data, application/x-www-form-urlencoded

Preflighted Requests (OPTIONS sent first):

  • Non-simple methods (PUT, DELETE, PATCH)
  • Custom headers (Authorization, X-Custom-Header)
  • Content-Type: application/json

Key CORS Headers:

  • Access-Control-Allow-Origin: Allowed origin(s) or *
  • Access-Control-Allow-Methods: Allowed HTTP methods
  • Access-Control-Allow-Headers: Allowed request headers
  • Access-Control-Allow-Credentials: Allow cookies/auth
  • Access-Control-Max-Age: Preflight cache duration

Code Examples

CORS error scenariosJavaScript
// Frontend code (https://myapp.com)

// This triggers CORS error if server doesn't allow it
fetch('https://api.other-domain.com/data')
  .then(res => res.json())
  .catch(err => {
    // "Access to fetch at 'https://api.other-domain.com/data' 
    // from origin 'https://myapp.com' has been blocked by CORS policy"
    console.error('CORS error:', err);
  });

// Preflight triggered by JSON content-type
fetch('https://api.other-domain.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json', // Triggers preflight!
  },
  body: JSON.stringify({ name: 'test' })
});

// Preflight triggered by custom header
fetch('https://api.other-domain.com/data', {
  headers: {
    'Authorization': 'Bearer token', // Triggers preflight!
    'X-Custom-Header': 'value'       // Also triggers preflight!
  }
});

Real-World Applications

Use Cases

Third-Party API Integration

Building a BFF (Backend for Frontend) proxy handling CORS, authentication, and rate-limiting for APIs like Stripe or OpenAI that require server-side calls

CDN Asset Serving

Configuring CORS headers on CDN-hosted fonts, images, and API responses with proper Vary header usage for correct caching

Microservices Gateway Configuration

Centralized API gateway handling preflight caching, credential forwarding, and per-route origin whitelisting across services

Mini Projects

CORS Debugging Proxy Server

intermediate

Build a local dev proxy that logs all CORS headers, visualizes preflight request/response pairs, and highlights misconfigurations

Secure API Gateway

advanced

Build Next.js App Router route handlers proxying to multiple backends with per-service CORS policies and JWT validation

Industry Examples

Stripe

Requires server-side API calls for sensitive operations; documentation recommends the BFF proxy pattern

Cloudflare Workers

Provides edge-based CORS handling and reverse proxy capabilities for cross-origin requests

AWS API Gateway

Built-in CORS configuration for REST and HTTP APIs with automatic OPTIONS preflight handling

Resources

MDN - Cross-Origin Resource Sharing (CORS)

docs

How to Debug Any CORS Error

article

CORS in 100 Seconds

video

Related Questions

What are Promises in JavaScript and how do they work?

mid
async

How do async/await work and how do they relate to Promises?

mid
async
Previous
Explain the Module pattern and how ES6 modules differ from CommonJS.
Next
How would you implement a debounce function from scratch with advanced features?
PrevNext