ReactMedium
What is CORS in React?
CORS (Cross-Origin Resource Sharing) is a browser security mechanism, not a React feature. When your React app on one origin (https://app.example.com) calls an API on another origin (https://api.example.com), the browser only lets your code read the response if the API sends matching Access-Control-Allow-* headers. CORS errors are fixed on the server or with a proxy, never in React code.
How it works
- Simple requests (GET, or POST with form content types) are sent; the browser checks
Access-Control-Allow-Originon the response. - Preflight: requests with custom headers (
Authorization), JSON content type, or methods like PUT/DELETE trigger anOPTIONSrequest first. The server must reply with allowed origins, methods and headers. - Credentials: sending cookies needs
credentials: "include"infetchandAccess-Control-Allow-Credentials: truewith an explicit origin (not*) on the server.
Fixes
- Configure the API to allow your origin (Express
corsmiddleware, framework settings, API gateway). - Development proxy: Vite
server.proxymakes requests same-origin during development. - Same-origin backend: call your own server or a backend-for-frontend (Next.js Route Handlers, React Router loaders) which calls the third-party API server-to-server, where CORS does not apply.
Common misconceptions
mode: "no-cors"does not fix anything; it produces an opaque response you cannot read.- Disabling CORS in the browser only hides the problem locally.
- CORS is not authentication; servers still need to verify who is calling.
Security
Do not reflect any Origin with credentials allowed; use an allowlist.
Code example
tsx
1// vite.config.ts - development proxy: the browser talks to the same origin2import { defineConfig } from "vite";3import react from "@vitejs/plugin-react";45export default defineConfig({6 plugins: [react()],7 server: {8 proxy: {9 "/api": { target: "http://localhost:8080", changeOrigin: true },10 },11 },12});1314// Client code: same-origin path in dev, full URL with credentials in prod15export async function getProfile() {16 const res = await fetch(`${import.meta.env.VITE_API_URL ?? ""}/api/profile`, {17 credentials: "include", // send cookies cross-origin (server must allow credentials)18 });19 return res.json();20}2122// Server side (Express) - the actual CORS fix23// import cors from "cors";24// app.use(cors({ origin: ["https://app.example.com"], credentials: true }));
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.