Data Fetching & APIs
React CORS and API Errors
A CORS error means the browser blocked a cross-origin response because the server did not send an Access-Control-Allow-Origin header permitting your site. It is a server configuration issue, not something React can fix.
What is CORS and API Errors in React?
A CORS error means the browser blocked a cross-origin response because the server did not send an Access-Control-Allow-Origin header permitting your site. It is a server configuration issue, not something React can fix.
Why CORS and API Errors matters
Nearly every beginner meets this on their first real API call, and the error message points at the browser rather than the actual cause, which sends people down the wrong path for hours.
CORS and API Errors example
// Express API — allow the front-end origin
import cors from 'cors';
app.use(cors({ origin: 'http://localhost:5173', credentials: true }));Development-only alternative: a Vite proxy
// vite.config.js — requests to /api are proxied, so the browser sees same-origin
export default defineConfig({
server: {
proxy: { '/api': { target: 'http://localhost:5000', changeOrigin: true } },
},
});Key points to remember
- CORS is enforced by the browser; the same request from Postman or curl succeeds.
- Requests with credentials require an explicit origin — the wildcard * is rejected.
- A failed preflight OPTIONS request produces the same symptom.
Common mistakes with CORS and API Errors
- Installing a "CORS unblock" browser extension and shipping code that only works on your machine.
- Setting the header on the front-end, which has no effect.
React CORS and API Errors— Interview Questions & FAQs
How do I fix a CORS error in React?+
Configure the API server to send Access-Control-Allow-Origin for your front-end origin. During development you can also proxy API calls through the dev server so the browser sees a same-origin request.
