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-Origin on the response.
  • Preflight: requests with custom headers (Authorization), JSON content type, or methods like PUT/DELETE trigger an OPTIONS request first. The server must reply with allowed origins, methods and headers.
  • Credentials: sending cookies needs credentials: "include" in fetch and Access-Control-Allow-Credentials: true with an explicit origin (not *) on the server.

Fixes

  1. Configure the API to allow your origin (Express cors middleware, framework settings, API gateway).
  2. Development proxy: Vite server.proxy makes requests same-origin during development.
  3. 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 origin
2import { defineConfig } from "vite";
3import react from "@vitejs/plugin-react";
4
5export default defineConfig({
6 plugins: [react()],
7 server: {
8 proxy: {
9 "/api": { target: "http://localhost:8080", changeOrigin: true },
10 },
11 },
12});
13
14// Client code: same-origin path in dev, full URL with credentials in prod
15export 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}
21
22// Server side (Express) - the actual CORS fix
23// 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.

Open in study app