A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
Generate a React client from FastAPI's /openapi.json, then hit the CORS wall: the API answers 200 but the browser blocks it. Fix it with CORSMiddleware, or avoid it with the Vite proxy and one VITE_API_URL variable.
What you will learn
- Generate a typed React client from FastAPI's own /openapi.json
- Explain what an origin is and why the browser blocks a cross-origin answer
- Allow a front-end origin with FastAPI's CORSMiddleware, including the preflight
- Avoid CORS in development with the Vite proxy and set the API address with VITE_API_URL
Before you start
- Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
- FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
Think of a typed order pad printed straight from the restaurant's menu. Nobody can order a dish that isn't on it. That is what you get when a React app's client is generated from the API's own spec. On the way there, though, almost everyone hits the same wall the first time: the API answers, and the browser refuses to hand the answer to the page.
This article connects a React app to a small FastAPI app, the Helpdesk API, and walks through that wall and the two ways around it. Every status and header below is from a saved run of the project.
One contract, two origins
FastAPI serves its own spec
A GET to /openapi.json answers 200 with one JSON document that starts {"openapi":"3.1.0","info":{"title":"Helpdesk API","version":"1"}. Its paths hold four operations, each with an id: list (GET /api/tickets), create (POST /api/tickets), get (one ticket) and addComment. FastAPI builds all of this from your routes and Pydantic models, so there is nothing extra to install. The app itself:
import os
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from tickets.errors import register_handlers
from tickets.routers import tickets
app = FastAPI(
title="Helpdesk API",
version="1",
openapi_tags=[{"name": "Tickets", "description": "Read and open support tickets"}],
)
app.include_router(tickets.router)
register_handlers(app)
# A bad body is answered with 400 (errors.py), never with FastAPI's default 422: take the 422 entries out of the
# contract, so the generated client has no types for an answer the API does not give.
def contract():
if app.openapi_schema is None:
spec = FastAPI.openapi(app)
for path in spec["paths"].values():
for operation in path.values():
operation["responses"].pop("422", None)
spec["components"]["schemas"].pop("HTTPValidationError", None)
spec["components"]["schemas"].pop("ValidationError", None)
return app.openapi_schema
app.openapi = contract
# CORS is off by default: the Vite dev server forwards /api, so the browser never makes a cross-origin call.
# CORS_ORIGINS=http://localhost:5173 lets a page from that origin read the answers.
if os.environ.get("CORS_ORIGINS"):
app.add_middleware(
CORSMiddleware,
allow_origins=os.environ["CORS_ORIGINS"].split(","),
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["Location"],
)
The contract() function removes the default 422 entries, because this API answers a bad body with 400 instead. Then the generated client has no types for an answer the API never gives. Keep the CORS block at the bottom in mind; we come back to it.
Orval turns the spec into a client
import { defineConfig } from 'orval'
import { operationName } from './orval.names'
export default defineConfig({
helpdesk: {
// Helpdesk's own contract, served by FastAPI
input: 'http://localhost:8080/openapi.json',
output: {
target: 'src/api/tickets.ts',
schemas: 'src/api/model',
client: 'react-query',
override: {
operationName,
mutator: {
path: 'src/api/fetcher.ts',
name: 'customFetch',
},
fetch: { includeHttpResponseReturnType: false },
},
},
},
})
The setup is the same as in the Orval article, pointed at FastAPI's /openapi.json. npm run api writes src/api/tickets.ts with a function and a hook per operation, and eleven model files in src/api/model. A small names file renames three operations:
import type { OperationObject } from 'orval'
// The spec calls the operations list, get, create ...
// These names read better in the code that uses them.
const names: Record<string, string> = {
list: 'getTickets',
get: 'getTicket',
create: 'createTicket',
}
export const operationName = (op: OperationObject) =>
names[op.operationId ?? ''] ?? op.operationId ?? ''
| Spec operation id | Our name | Hook |
|---|---|---|
list | getTickets | useGetTickets |
get | getTicket | useGetTicket |
create | createTicket | useCreateTicket |
addComment | (no entry, kept) | useAddComment |
A schema becomes a typed field
Two generated files, src/api/model/ticketSummary.ts and ticketSummaryStatus.ts (after their comment header):
import type { TicketSummaryPriority } from './ticketSummaryPriority';
import type { TicketSummaryStatus } from './ticketSummaryStatus';
export interface TicketSummary {
id: number;
subject: string;
status: TicketSummaryStatus;
priority: TicketSummaryPriority;
customer: string;
assignee?: string | null;
createdAt: string;
}
export type TicketSummaryStatus = typeof TicketSummaryStatus[keyof typeof TicketSummaryStatus];
export const TicketSummaryStatus = {
OPEN: 'OPEN',
IN_PROGRESS: 'IN_PROGRESS',
RESOLVED: 'RESOLVED',
CLOSED: 'CLOSED',
} as const;
status is an enum in the spec, so the field only allows four values. A ticket may have no assignee, so assignee is string | null and optional. Every other field is required, because the FastAPI models say it always has a value.
One hook gives typed rows
import { useGetTickets } from './api/tickets'
export default function TicketList() {
// generated: typed rows, one request, cached
const { data, isPending, error } = useGetTickets()
if (isPending) return <p>Loading tickets...</p>
if (error) return <p>{error.message}</p>
return (
<table>
<tbody>
{data.map((t) => (
<tr key={t.id}>
<td>#{t.id}</td>
<td>{t.subject}</td>
<td>{t.priority}</td>
<td>{t.status}</td>
</tr>
))}
</tbody>
</table>
)
}
The hook sends GET /api/tickets and fifty tickets come back. While the request is on its way the page shows Loading tickets..., then one row per ticket: #1 Cannot log in after password reset, #2 Invoice shows the wrong amount, #3 How do I export my data to CSV. The component never builds a URL and never parses JSON.
One place touches the network
// The one place that touches the network. The generated
// code calls it for every request; this file is ours.
// One variable says where the API lives. Empty in
// development: calls stay on :5173 and the dev proxy
// forwards them to :8080, so there is no CORS.
const base = import.meta.env.VITE_API_URL ?? ''
export class ApiError extends Error {
status: number
body: unknown
constructor(status: number, body: unknown) {
super(`HTTP ${status}`)
this.status = status
this.body = body
}
}
// the generated hooks use this as their error type
export type ErrorType<T = unknown> =
T extends unknown ? ApiError : never
export async function customFetch<T>(
url: string,
options: RequestInit,
): Promise<T> {
// BREAK IT: base = 'http://localhost:8080' in dev
// and the browser blocks the answer (CORS)
const res = await fetch(base + url, options)
const text = await res.text()
const body = text ? JSON.parse(text) : undefined
if (!res.ok) throw new ApiError(res.status, body)
return body as T
}
Every generated call goes through customFetch. base comes from VITE_API_URL, and in development it is not set, so base is an empty string. The hook asks for /api/tickets, and '' + '/api/tickets' is a relative URL. The browser adds the page's own origin: http://localhost:5173/api/tickets. Hold that thought.
The CORS wall
Break it on purpose: make the page call the API directly at http://localhost:8080. Because the request goes to another origin, the browser adds an Origin header. With CORS off, the run recorded:
GET /api/tickets
Origin: http://localhost:5173
-> 200, Content-Type: application/json (no Access-Control-Allow-Origin header)
The API answered 200 with the tickets. It just never said who may read them. The answer arrives inside the browser, the browser sees it came from another origin, looks for Access-Control-Allow-Origin, does not find it, and holds the answer back. The page's code gets:
TypeError: Failed to fetch
This is the part people often get wrong. The server did answer. The browser is the one saying no.
Way 1: tell the browser who may read (CORSMiddleware)
Look again at the bottom of main.py. CORSMiddleware takes allow_origins, the origins that may read the answers. Here the list comes from the CORS_ORIGINS environment variable, so it can change without touching the code:
export CORS_ORIGINS=http://localhost:5173 # Windows: set CORS_ORIGINS=http://localhost:5173
uvicorn tickets.main:app --port 8080
Now the same request comes back with the permission slip, and a different origin still gets none:
Origin: http://localhost:5173 -> 200, Access-Control-Allow-Origin: http://localhost:5173, Vary: Origin
Origin: http://localhost:9999 -> 200, no Access-Control-Allow-Origin
For a POST with a JSON body, the browser asks first with an OPTIONS request, the preflight:
OPTIONS /api/tickets
Origin: http://localhost:5173
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
-> 200
Access-Control-Allow-Origin: http://localhost:5173
Access-Control-Allow-Methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT, QUERY
Access-Control-Allow-Headers: content-type
Access-Control-Max-Age: 600
The browser may keep that answer for 600 seconds before asking again. In the browser run, with CORS_ORIGINS set, the same direct fetch that failed before returned 200 with 50 tickets.
Way 2: keep the browser on its own origin (Vite proxy)
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [react()],
server: {
// the browser asks :5173, the dev server asks :8080
proxy: { '/api': 'http://localhost:8080' },
},
})
Anything starting with /api goes to port 8080. The page asks for /api/tickets on its own origin, the Vite dev server, so there is nothing to check. Vite forwards the request to localhost:8080. That hop is server to server, with no browser in it, so no CORS rule applies. The answer goes back to Vite and back to the page, and the page shows its fifty rows. This is why the API in this project has CORS off by default.
One variable says where the API lives
| Development | Production | |
|---|---|---|
VITE_API_URL | not set | set in .env.production |
base in fetcher.ts | empty string | the deployed API's address |
| Who forwards the call | Vite proxy, same origin | nobody: a cross-origin call |
| Needs CORSMiddleware? | no | yes, with the site's origin |
# where the deployed API lives; read in src/api/fetcher.ts
VITE_API_URL=https://api.helpdesk.example
In production there is no dev server, so the address comes from the variable and the fetcher puts it in front of every call. That call is cross-origin again, so the deployed API needs the middleware with your site's origin in allow_origins. (The production variant was not part of the saved run.)
Common mistakes
- Debugging the server for a CORS error. The server answered 200. The fix is a header from the server or a same-origin path, not a change to the route.
- Setting VITE_API_URL in development. The browser then calls port 8080 directly and hits the wall. The comment in
fetcher.tsmarks exactly that break. - Forgetting the preflight. A POST with JSON sends
OPTIONSfirst; the middleware has to allow the method and thecontent-typeheader.
Quick recap
| Step | What happens |
|---|---|
| FastAPI serves the spec | /openapi.json, four operations |
| Orval writes the client | useGetTickets and eleven model files |
| Two ports, two origins | The browser blocks the answer: Failed to fetch |
| CORSMiddleware | Access-Control-Allow-Origin for listed origins |
| Vite proxy | Same origin in development, no CORS |
VITE_API_URL | Empty in development, set once for production |
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Server State With TanStack Query: One Key, One Request, One Cache
Three components need the same list of books. Fetch it by hand and you get three requests; ask TanStack Query for one key and you get one. With real request counts, retries and a quiet refetch on tab focus.
Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
Add a book with useMutation and let invalidateQueries refetch the list, then make delete instant: snapshot, remove the row in 3 ms, roll back on a 404 and refetch the truth in onSettled.
Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
Let the API's OpenAPI spec write your React client: Orval turns /v3/api-docs into TypeScript types, useGetBooks and a Zod schema, and a renamed field becomes error TS2339 at BookList.tsx line 26.
A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
Build the React screen before the API exists: Orval writes MSW handlers and faker data from the spec, a service worker answers GET /api/books inside the browser, and npm run dev:real switches back to the real server.
