Fossils🌐 Web PlatformExplain CORS and How to Debug It
ðŸĢHatchlingBrowserSecurityHTTP

Explain CORS and How to Debug It

CORS errors are the bane of frontend development. Understanding the mechanism separates debugging from guessing.

Explain CORS and How to Debug It

Every frontend developer has hit a CORS error. Seniors understand why it exists and how to fix it properly.

What CORS Is

Cross-Origin Resource Sharing is a browser security mechanism. It prevents JavaScript on origin-a.com from reading responses from origin-b.com unless origin-b.com explicitly allows it.

An "origin" is: protocol + hostname + port. Even http://localhost:3000 and http://localhost:4000 are different origins.

How It Works

Simple Requests

For GET/POST with standard headers, the browser sends the request directly with an Origin header:

GET /api/data HTTP/1.1
Host: api.example.com
Origin: https://app.example.com

The server responds with:

Access-Control-Allow-Origin: https://app.example.com

If the header is missing or doesn't match, the browser blocks JavaScript from reading the response.

Preflight Requests

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

OPTIONS /api/data HTTP/1.1
Origin: https://app.example.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: Content-Type, Authorization

The server must respond with:

Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, PUT, POST, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 86400

Common Mistakes

  1. Using * with credentials — Access-Control-Allow-Origin: * cannot be used with credentials: 'include'
  2. Missing preflight handling — server must respond to OPTIONS requests
  3. Proxy confusion — CORS is a browser-only restriction; server-to-server requests skip it entirely
  4. Caching issues — Vary: Origin is needed when multiple origins are allowed

Debugging Checklist

  1. Check the Network tab for the preflight OPTIONS request
  2. Verify the response headers include the correct Access-Control-Allow-* values
  3. Check if credentials mode requires a specific origin (not *)
  4. Confirm the server handles OPTIONS method
  5. Check if a proxy or CDN is stripping CORS headers

CORS isn't a bug — it's a security feature. The fix is always on the server, never a browser hack.