CORS (Cross-Origin Resource Sharing)

CORS is a browser security mechanism that controls which websites can make requests to your API. By default, browsers block requests from one domain to another — CORS headers tell the browser which cross-origin requests to allow. For vibe coders, CORS errors are among the most common and confusing issues encountered.

Example

Your frontend at localhost:3000 tries to call your API at localhost:8080. The browser blocks it with a CORS error because they're different origins (different ports). Adding CORS headers to your API tells the browser 'requests from localhost:3000 are allowed.'

CORS errors are a rite of passage for every developer. They look scary but have a simple fix once you understand what's happening.

Why CORS Exists

CORS is a security feature. Without it, any website could:

  • Read your private data from other sites
  • Make requests to your bank while you're logged in
  • Access APIs they shouldn't have access to

CORS prevents this by requiring explicit permission for cross-origin requests.

What's an "Origin"?

An origin is a combination of protocol + domain + port:

URLOrigin
http://localhost:3000localhost:3000
http://localhost:8080localhost:8080 (different!)
https://myapp.commyapp.com
https://api.myapp.comapi.myapp.com (different!)

The CORS Error

Access to fetch at 'http://localhost:8080/api/data'
from origin 'http://localhost:3000' has been blocked by CORS policy

This means: "Your API didn't say this origin is allowed."

Fixing CORS

Add CORS headers to your API response:

// Allow requests from your frontend
headers: {
  'Access-Control-Allow-Origin': 'http://localhost:3000',
  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
}

When CORS Isn't an Issue

If your frontend and API share the same origin (like Next.js API routes), CORS doesn't apply. This is one reason Next.js is popular for vibe coding — the frontend and backend share an origin by default.