React / 32
CORS: why the browser blocked your fetch
The browser only lets your page read another origin's response if that server says so in its headers. What's blocked, what a preflight is, and the only real fixes.
First, the same-origin policy
Browsers follow a rule called the same-origin policy: JavaScript on a page can freely read responses only from its own origin. An origin is the scheme, host and port together:
compared with a page on https://app.example.com
https://app.example.com/menusame origin · only the path differshttp://app.example.comcross-origin · different schemehttps://api.example.comcross-origin · different hosthttp://localhost:5173 → :3000cross-origin · different port
Why so strict? You're logged in to your bank in one tab. Without this rule, any other site you visit could run fetch("https://yourbank.com/statements"), the browser would attach your bank cookies, and that site could read the result. The same-origin policy stops other sites from reading responses meant for you.
CORS: the server gives permission
CORS (Cross-Origin Resource Sharing) is how a server opts in to sharing with other origins. It's just HTTP headers. The browser sends an Origin header with your request, and the server answers with Access-Control-Allow-Origin, naming the origins that may read the response.
What the browser and server say
Try ityour fetch()
the API server
Browser
localhost:5173
Server
api.example.com
- browser → server
GET /recipesOrigin: http://localhost:5173 - server → browser
200 OKAccess-Control-Allow-Origin: http://localhost:5173{ "recipes": [ … ] } - ✓Header matches your origin. fetch() gets the data.
Simple requests vs preflight
- Simple requests (
GET,HEAD, orPOSTwith a form or plain-textContent-Type, and only basic headers) go straight out. The browser checks the response headers afterwards. If permission is missing, the server has already done the work, and your code just can't see the result. - Everything else gets a preflight. That includes
PUT,PATCH,DELETE, aContent-Type: application/jsonbody, or custom headers likeAuthorization. The browser first sends an automaticOPTIONSrequest asking "may I?". The real request goes out only if the server approves. AnAccess-Control-Max-Ageheader lets the browser cache that approval.
So a cross-origin JSON POST always triggers a preflight. If you see an OPTIONS request in the Network tab you didn't write, that's it.
How the server allows it
On the server it's a few headers. In Node with Express, the cors middleware sets them (and answers preflights) for you:
import express from "express";
import cors from "cors";
const app = express();
app.use(cors({ origin: ["http://localhost:5173", "https://app.example.com"] }));
app.get("/recipes", (req, res) => res.json({ recipes: [] }));
app.listen(3000);List the exact origins you trust. Access-Control-Allow-Origin: * (anyone) is fine for a truly public API, but it can't be used for requests that send cookies (credentials: "include"). For those, the server must name your origin exactly.
Fixes, ranked
| Fix | Where | Use in production? |
|---|---|---|
| Server sends CORS headers for your origin | The API server | Yes. This is the real fix. |
| Call the API from your own backend, then call your backend | Your server or a serverless function | Yes. Needed for APIs you don't control, and it keeps API keys secret. |
Dev-server proxy (Vite server.proxy) | Your dev machine | Development only |
| A "CORS unblock" browser extension | Your browser | Never. Your users don't have it. |
A dev proxy makes the browser think the API is on your own origin. Vite forwards the request server-to-server, where CORS doesn't apply:
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [react()],
server: {
proxy: {
"/api": {
target: "https://api.example.com",
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ""),
},
},
},
});Now fetch("/api/recipes") works in npm run dev. The proxy doesn't exist after vite build, so production still needs one of the real fixes.
Gotchas
Recall
Can you answer these?
0/5
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
