Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

React
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
  • How a Web Page Works: HTML Tags, Elements and Attributes
  • Semantic HTML: header, nav, main, aside and footer as Page Landmarks
  • HTML Forms: Labels, Names, Input Types and Where the Data Goes (GET vs POST)
  • CSS Basics: Selectors, Which Rule Wins, and the Box Model
  • CSS Flexbox vs Grid: A Nav Bar, a Card Row and a Dashboard
  • Responsive CSS: Viewport, Mobile-First Media Queries, clamp() and Dark Mode with Tokens
  • JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
  • JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
  • Async JavaScript: Promises, async/await, fetch and Promise.all
  • JavaScript in the Page: the DOM, querySelector and Events
  • npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
  • TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)
  • Why React, JSX and Components: The Page as a Function of Data
  • React Props and Composition: Data Down, Calls Up, Children in the Slot
  • Routing With React Router: One Page, Many Addresses
  • React Component Tests With Vitest and Testing Library: Test What the User Sees
  • End-to-End Tests for a React App With Playwright: A Full Dress Rehearsal
  • Why AI-Built Websites All Look the Same, and Four Levels That Fix It
  • Visual Hierarchy, Spacing and the 8-Point Grid: Tell the Eye What to Read First
  • Colour, Contrast and Dark Palettes: 60-30-10, Semantic Tokens and Ratios You Can Compute
  • Typography That Sells: Type Scale, Line Length and Free Font Pairings
  • The UI Element Catalogue: Buttons to Toasts, Their Jobs, States and shadcn/ui Names
  • Design Tokens: Primitive and Semantic Tokens, from Figma to CSS to Tailwind
  • Tailwind CSS 4 in React: Utility Classes, Responsive Prefixes, Hover and Dark Mode
  • shadcn/ui in React: Components You Own, Edit and Commit
  • Design Tokens to a Tailwind Theme: Light and Dark Mode with @theme inline
  • Motion in React: Entrance, Hover, Exit and Layout Animations
  • A React Dashboard: Stat Cards, a Recharts Line Chart and a Sortable Table
  • Accessibility in Practice: Dialogs, Menus and the Keyboard in React
  • Reference-Driven Design: Extract a DESIGN.md From a Site You Admire and Build From It
  • Components, Variants and Variables: One Design System in Figma and in CSS
  • Figma MCP Server: Build a React Component From a Frame, Then Write It Back
  • Claude Design: From a Brief to a Clickable Prototype, Then Hand It Off to Claude Code
  • Critiquing AI-Generated UI: Six Checks for Every Screen
  • The AI Design Landscape: Prompt to UI, Prompt to App, and Design to Code
  • Your Brand Rules Folder: One Folder Every AI-Built Page Follows
  • The Best-Practice UI Prompt: Plain Sentences That Beat the Average AI Page
  • UI Ideas From Figma Make, Google Stitch and ChatGPT: One Prompt, Three Designs
  • Google Stitch From a Sketch or Screenshot: Show the Layout, Say What to Keep
  • Stitch to Figma to Code: Turn a Stitch Screen Into Code That Uses Your Tokens
  • Figma Make: Prompt to Prototype With a Four-Part Prompt
  • Upgrade a Dated UI From One Screenshot (or a Reference Image)
  • States and Feedback: Make Every Click Get an Answer
  • A Design-Loop Skill: Claude Screenshots, Scores and Fixes Its Own UI
  • Copy Without the AI Tells: A Copy Pass on a Landing Page
  • React State, Events, Lists and Conditional Rendering: Follow One Click
  • React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
  • Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
  • Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
  • React Context and Custom Hooks: Share One Value, Reuse the Logic
  • Server State With TanStack Query: One Key, One Request, One Cache
  • Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
  • JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
  1. Blog
  2. /
  3. React
  4. /
  5. Working with APIs

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Working with APIs

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

One contract, two origins Helpdesk API FastAPI /openapi.json Orval Helpdesk React app src/api: hooks, types http://localhost:8080 http://localhost:5173 same host, different port: two origins
Scheme, host and port together make an origin. Change any one of them and it is a different origin.

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 idOur nameHook
listgetTicketsuseGetTickets
getgetTicketuseGetTicket
createcreateTicketuseCreateTicket
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.

The browser blocks the answer browser page :5173 CORS check header missing API :8080 200, tickets GET /api/tickets TypeError: Failed to fetch
The request reaches the server and the answer comes back. The browser holds it back because nothing says this origin may read it.

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

DevelopmentProduction
VITE_API_URLnot setset in .env.production
base in fetcher.tsempty stringthe deployed API's address
Who forwards the callVite proxy, same originnobody: a cross-origin call
Needs CORSMiddleware?noyes, 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.ts marks exactly that break.
  • Forgetting the preflight. A POST with JSON sends OPTIONS first; the middleware has to allow the method and the content-type header.

Quick recap

StepWhat happens
FastAPI serves the spec/openapi.json, four operations
Orval writes the clientuseGetTickets and eleven model files
Two ports, two originsThe browser blocks the answer: Failed to fetch
CORSMiddlewareAccess-Control-Allow-Origin for listed origins
Vite proxySame origin in development, no CORS
VITE_API_URLEmpty in development, set once for production

Keep going in React · 57 of 59

Previous
A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
Next post
Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • One contract, two origins
  • FastAPI serves its own spec
  • Orval turns the spec into a client
  • A schema becomes a typed field
  • One hook gives typed rows
  • One place touches the network
  • The CORS wall
  • Way 1: tell the browser who may read (CORSMiddleware)
  • Way 2: keep the browser on its own origin (Vite proxy)
  • One variable says where the API lives
  • Common mistakes
  • Quick recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.