Typical Browser Console Error (React (Vite) → Python FastAPI)
When cross-origin headers are missing, mismatched, or blocked during preflight between React (Vite) and Python FastAPI, Chrome and Firefox log an error matching the pattern below in DevTools:
Access to fetch at 'http://localhost:8000/api/items/42' from origin 'http://localhost:5173' has been blocked by CORS policy: Request header field x-client-version is not allowed by Access-Control-Allow-Headers in preflight response.
Why CORS Blocks Requests Between React (Vite) and Python FastAPI
Pairing a Python FastAPI backend running on Uvicorn at http://localhost:8000 with a React + Vite frontend on http://localhost:5173 gives full-stack teams instantaneous hot module replacement alongside automatic OpenAPI schema validation. However, because Vite serves the React bundle on port 5173 and Uvicorn listens on port 8000, every browser fetch() or Axios request crosses an origin boundary and must pass the browser's strict CORS policy enforcement.
Even when developers remember to register CORSMiddleware with http://localhost:5173, React SPAs frequently encounter preflight rejections on non-simple HTTP methods like DELETE, PUT, and PATCH, or whenever custom application headers such as X-Client-Version, X-Request-ID, or Authorization are attached. Because none of these headers are CORS-safelisted, the browser automatically dispatches an OPTIONS preflight request carrying Access-Control-Request-Method and Access-Control-Request-Headers before touching your Python route handler.
Furthermore, multipart file uploads, streaming Server-Sent Events (SSE) for real-time AI token responses, and downloadable CSV or PDF exports frequently appear broken in React because custom response headers like Content-Disposition or X-Total-Count remain invisible to client-side JavaScript unless explicitly declared in FastAPI's expose_headers list. Validating both request and response header policies up front prevents subtle regressions across staging and production deployments.
During both local development and CI smoke testing, validating the complete FastAPI + React Vite preflight lifecycle catches subtle drift whenever frontend engineers introduce a new custom header (such as X-Workspace-Id or X-Trace-Id) or a new HTTP verb like PATCH. Use the interactive simulator above to test your exact combination of method, Content-Type, and custom headers, then compare the simulated Access-Control-Allow-* headers against your live Uvicorn response in Chrome DevTools. Keeping expose_headers and allow_headers explicitly synchronized in backend/main.py ensures pagination metadata, file download names, and authenticated mutations work identically across every browser.
Step-by-Step Python FastAPI + React (Vite) CORS Fix Guide
Follow each step below in order to eliminate preflight failures and lock down production origins safely for Python FastAPI.
1Configure FastAPI CORSMiddleware for Vite Origins and Custom Headers
backend/main.pyWhitelist http://localhost:5173 (plus http://127.0.0.1:5173 if teammates alternate local hostnames), enumerate every REST method including DELETE and PATCH, and explicitly list both incoming custom headers in allow_headers and readable response headers in expose_headers.
backend/main.pypythonfrom fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() origins = [ "http://localhost:5173", "http://127.0.0.1:5173", ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=False, allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], allow_headers=["Content-Type", "Authorization", "X-Client-Version"], expose_headers=["Content-Disposition", "X-Total-Count"], max_age=86400, )2Bind Uvicorn Cleanly and Verify OPTIONS Preflight Responses via curl
terminal (backend directory)Start Uvicorn on port 8000 and reproduce the exact browser OPTIONS preflight handshake from your terminal before debugging React state. Confirm FastAPI returns HTTP 200 OK along with Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers covering every requested header.
terminal (backend directory)bashuvicorn backend.main:app --reload --host 0.0.0.0 --port 8000 # Verify preflight headers from terminal: curl -i -X OPTIONS http://localhost:8000/api/items/42 \ -H "Origin: http://localhost:5173" \ -H "Access-Control-Request-Method: DELETE" \ -H "Access-Control-Request-Headers: authorization, x-client-version"3Handle Authenticated Mutations and Multipart Uploads Safely in React
frontend/src/lib/itemsApi.tsKeep your API origin configurable via VITE_API_BASE_URL and attach only the custom headers explicitly authorized by FastAPI. When uploading files to a FastAPI UploadFile endpoint using FormData, never manually set Content-Type: multipart/form-data; let the browser inject the multipart boundary automatically while Authorization stays whitelisted.
frontend/src/lib/itemsApi.tstypescriptconst API_BASE = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:8000'; export async function deleteItem(itemId: number, token: string) { const response = await fetch(`${API_BASE}/api/items/${itemId}`, { method: 'DELETE', headers: { Authorization: `Bearer ${token}`, 'X-Client-Version': '1.4.0', }, }); if (!response.ok) { throw new Error(`Delete failed with HTTP ${response.status}`); } return response.json(); }4Read Exposed Response Headers for File Downloads and Pagination
frontend/src/lib/export.tsBy default, browsers only allow JavaScript to read seven CORS-safelisted response headers. Once Content-Disposition and X-Total-Count are added to FastAPI's expose_headers parameter, your React pagination hooks and file export utilities can safely inspect them via response.headers.get().
frontend/src/lib/export.tstypescriptexport async function fetchPaginatedItems(token: string) { const res = await fetch('http://localhost:8000/api/items', { headers: { Authorization: `Bearer ${token}` }, }); const totalCount = Number(res.headers.get('X-Total-Count') ?? '0'); const items = await res.json(); return { items, totalCount }; }
Common Python FastAPI + React (Vite) CORS Pitfalls
Even when your basic origin string looks correct, these three framework-specific edge cases frequently reintroduce CORS failures in staging and production environments.
Custom Headers Blocked Even When Origin Matches Perfectly
Developers often assume that once Access-Control-Allow-Origin matches http://localhost:5173, any custom header like X-Client-Version or X-API-Key will pass automatically. In reality, browsers compare every non-safelisted request header case-insensitively against Access-Control-Allow-Headers during preflight and abort the call if even a single header is missing.
Using allow_origins=["http://localhost:5173/"] With a Trailing Slash
Copying the React URL straight from Chrome's address bar into FastAPI's origins list frequently leaves a trailing slash behind. Because browsers transmit Origin: http://localhost:5173 without a trailing slash, Starlette's exact string check fails and omits Access-Control-Allow-Origin completely.
StreamingResponse and Validation Errors Losing Expected Headers
When streaming Server-Sent Events or chunked LLM completions from FastAPI to React, HTTP headers are flushed the moment streaming starts. While FastAPI's 422 Pydantic validation errors pass through CORSMiddleware normally, uncaught Python exceptions inside generator streams or middleware registered after CORSMiddleware can drop CORS headers.
Deploying Behind Nginx? Eliminate CORS Preflights or Configure Your Proxy
Configure TLS, WebSocket headers, and X-Forwarded-Proto, or serve your frontend and /api/ on the same origin with Nginx Reverse Proxy Config for FastAPI + Uvicorn (SSL, Docs & Timeouts).
Frequently Asked Questions
- Why does React return null for response.headers.get("X-Total-Count") even though it appears in Chrome DevTools?
- Chrome DevTools displays every raw HTTP response header transmitted over the wire, but the Fetch Standard hides non-safelisted response headers from JavaScript unless the backend returns Access-Control-Expose-Headers. Add expose_headers=["X-Total-Count"] to FastAPI's CORSMiddleware configuration.
- Why does FastAPI return HTTP 400 Disallowed CORS method or headers on OPTIONS?
- Starlette's CORSMiddleware actively inspects Access-Control-Request-Method and Access-Control-Request-Headers on incoming OPTIONS preflights and returns HTTP 400 with a descriptive plain-text message naming the exact disallowed method or header. Click the failed OPTIONS call in Chrome DevTools and read the Response tab body.
- Can I configure Vite server.proxy during development and CORSMiddleware for production?
- Yes, though testing against FastAPI's real CORSMiddleware during local development surfaces missing custom headers, trailing-slash 307 redirects, and credential errors long before deployment. If you rely on Vite's proxy locally, run a pre-release verification test against your cross-origin staging URL.
- How does max_age improve FastAPI + React performance?
- Setting max_age=86400 instructs browsers to cache approved OPTIONS preflight responses up to each browser's ceiling (2 hours in Chromium and 24 hours in Firefox), eliminating redundant OPTIONS round-trips before repeated DELETE, PUT, PATCH, or JSON POST mutations.
Related CORS Stack Simulators
Browse all 12 stacks →FastAPI + Next.js CORS Config Simulator & Fix Guide
Fix CORS preflight failures between Python FastAPI (Uvicorn) and Next.js on port 3000. Configure CORSMiddleware order, trailing redirects, and credentials.
Laravel + React (Vite) CORS Config Simulator & Fix Guide
Simulate and fix CORS preflight errors between Laravel 11/12 APIs and React Vite on port 5173. Generate config/cors.php with credentials and header rules.
Node.js Express + React (Vite) CORS Config Simulator & Fix Guide
Resolve CORS preflight errors between Node.js Express APIs and React Vite on port 5173. Generate cors() configs, fix PATCH/DELETE methods, and debug headers.
ASP.NET Core Web API + React CORS Config Simulator & Fix Guide
Simulate and fix CORS preflight errors between ASP.NET Core 8/9 Web API and React (Vite/CRA). Debug Minimal APIs, Dev Certs, exposed headers, and cookies.