Skip to content
ClapelloNotes by Barath
ReactCh 06 · 5/6
Core5 min readUpdated

React / 32

CORS: why the browser blocked your fetch

TL;DR

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:

schemehttps://
hostapp.example.com
port:443

compared with a page on https://app.example.com

  • https://app.example.com/menusame origin · only the path differs
  • http://app.example.comcross-origin · different scheme
  • https://api.example.comcross-origin · different host
  • http://localhost:5173 → :3000cross-origin · different port
Same origin = same scheme + host + port. Change any one of them and the request is cross-origin.

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 it

your fetch()

the API server

Browser
localhost:5173

Server
api.example.com

  1. browser → server
    GET /recipesOrigin: http://localhost:5173
  2. server → browser
    200 OKAccess-Control-Allow-Origin: http://localhost:5173{ "recipes": [ … ] }
  3. ✓Header matches your origin. fetch() gets the data.
Your page runs on localhost:5173 and calls https://api.example.com. Switch the request type and the server's CORS setup and compare the messages.

Simple requests vs preflight

  • Simple requests (GET, HEAD, or POST with a form or plain-text Content-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, a Content-Type: application/json body, or custom headers like Authorization. The browser first sends an automatic OPTIONS request asking "may I?". The real request goes out only if the server approves. An Access-Control-Max-Age header 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:

server.js
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

FixWhereUse in production?
Server sends CORS headers for your originThe API serverYes. This is the real fix.
Call the API from your own backend, then call your backendYour server or a serverless functionYes. Needed for APIs you don't control, and it keeps API keys secret.
Dev-server proxy (Vite server.proxy)Your dev machineDevelopment only
A "CORS unblock" browser extensionYour browserNever. 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:

vite.config.js
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.