CORS & Preflight Simulator · Python FastAPI + React (Vite)

FastAPI + React (Vite) CORS Config Simulator & Fix Guide

Simulate Fetch Standard preflight (OPTIONS) triggers, credential rules, and origin matching between React (Vite) and Python FastAPI. Copy generated configuration code below.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust stack settings or load a test scenario2. Inspect live diagnostics3. Copy generated config
Quick-Test Scenarios:

1. Browser Request (React (Vite))

2. Server Response Policy (Python FastAPI)

Access-Control-Allow-Methods
# main.py — FastAPI CORSMiddleware
# Register CORSMiddleware BEFORE custom auth/error middleware so error responses retain CORS headers.
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins = [
    "http://localhost: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"],
    max_age=86400,
)

Preflight (OPTIONS)

Triggered · Passed

HTTP method "DELETE" is not a CORS-safelisted method (only GET, HEAD, and POST skip preflight). Content-Type "application/json" is not CORS-safelisted (only application/x-www-form-urlencoded, multipart/form-data, and text/plain avoid preflight). Request includes non-safelisted header(s): Authorization, X-Client-Version.

Browser Verdict

Allowed

Browser CORS validation passed. JavaScript can read the response body.

Rule Engine Diagnostics

  • Reverse Proxy Tip: Avoid Duplicate CORS Headers in Nginx + Upstream App

    Never configure Access-Control-Allow-Origin in both Nginx and your backend framework simultaneously. Browsers reject duplicate headers with: "The 'Access-Control-Allow-Origin' header contains multiple values '*, http://localhost:5173', but only one is allowed." Choose one layer (or use proxy_hide_header in Nginx).

Simulated HTTP Response Headers

HTTP/1.1
Preflight (OPTIONS)
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: http://localhost:5173
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization, X-Client-Version
Access-Control-Max-Age: 86400
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
Actual Response (DELETE)
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://localhost:5173
Vary: Origin

Runs locally in your browser. Origins, endpoints, and headers are never sent to a server.

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:

DevTools Console Output

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.

  1. 1Configure FastAPI CORSMiddleware for Vite Origins and Custom Headers

    backend/main.py

    Whitelist 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.pypython
    from 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,
    )
  2. 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)bash
    uvicorn 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"
  3. 3Handle Authenticated Mutations and Multipart Uploads Safely in React

    frontend/src/lib/itemsApi.ts

    Keep 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.tstypescript
    const 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();
    }
  4. 4Read Exposed Response Headers for File Downloads and Pagination

    frontend/src/lib/export.ts

    By 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.tstypescript
    export 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.

Pitfall 1

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.

Pitfall 2

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.

Pitfall 3

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.

Related Tool · Same-Origin Reverse 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).

Open Nginx Builder

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.
Browse all 12 stacks →