"Blocked by CORS policy" โ every developer's rite of passage. Understand the WHY and the error becomes routine.
The why
Browsers block JS on site A from reading responses from site B โ otherwise any webpage could silently read your Gmail using your logged-in cookies. That's the same-origin policy. CORS is servers opting OUT: "these other origins may read my responses".
The mechanics
// your page on localhost:3000 fetches api.site.com // browser adds: Origin: http://localhost:3000 // server must reply: Access-Control-Allow-Origin: http://localhost:3000 // header present โ JS gets the data; absent โ CORS error // "non-simple" requests (JSON POST, auth headers) trigger a PREFLIGHT: // browser first sends OPTIONS asking permission โ that's the mystery // OPTIONS request in your Network tab
The fixes (it's ALWAYS the server)
// your own Express API:
import cors from "cors";
app.use(cors({ origin: "http://localhost:3000" }));- Third-party API without CORS? Proxy it through YOUR backend (server-to-server has no CORS)
- Dev servers (Vite) have a built-in proxy config for exactly this
- Things that never work: adding headers to your fetch (the SERVER grants permission), disabling browser security
Interview line: "CORS is enforced by the browser, configured by the server, and protects the user โ not the API."
โ All Articles