Connect React or Next.js to FastAPI
Call FastAPI from a Next.js client with the right CORS or proxy setup, typed requests and clear UI states.
By Invicly Tech, , in FastAPI with Python for AI Backends. About 10 minutes to read.
In short
A Next.js frontend and a FastAPI backend usually run on different origins, so the browser applies CORS rules to every call between them. You either allow the frontend's origin in FastAPI or route calls through a same-origin proxy such as Next.js rewrites. Generate TypeScript types from FastAPI's OpenAPI schema so the client and server agree on every request and response.
Think of it like this: CORS is a guest list at the door of the API; a same-origin proxy is a friend inside who carries messages in for you.
Explained simply
A typical AI app has two parts: a Next.js frontend that runs in the browser and a FastAPI backend that holds the data and calls the model. During development they run on two ports, such as 3000 and 8000. To the browser, those are two different websites.
Browsers protect users by blocking a page from reading responses from another origin unless that origin agrees. This agreement is called CORS. FastAPI can send CORS headers that say which frontend origins are allowed. The other choice is a proxy: the browser only talks to the Next.js site, and Next.js passes calls on to FastAPI.
Both sides must agree on what each request and response looks like. FastAPI already describes its API in a file called openapi.json. A tool can turn that file into TypeScript types, so your editor warns you when the frontend sends the wrong shape.
Users also need to see what is happening. An upload goes from choosing a file, to uploading, to processing, to ready or failed. If each step has its own clear message, people trust the app and know when to try again.
Press Play on a diagram to walk through it one step at a time.
- Browser calls api.example.com
- FastAPI lists allowed origins
- Preflight OPTIONS for many requests
- Cookies need allow_credentials and exact origins
- Browser calls /api on the site
- Next.js forwards to FastAPI
- No CORS needed in the browser
- Cookies stay first-party
- 1Idle
File picker enabled
- 2Uploading
Progress shown, button disabled
- 3Queued
202 received, job ID stored
- 4Processing
Polling GET /jobs/{id}
- 5Ready or failed
Show document, or the error and a retry
In depth
How the browser decides on CORS
For simple requests, such as a GET without custom headers, the browser sends the request and then checks the Access-Control-Allow-Origin header on the response. For anything else, such as a POST with a JSON body or an Authorization header, it first sends a preflight OPTIONS request asking which methods and headers are allowed. FastAPI's CORSMiddleware answers both.
CORS is enforced by the browser only. It does not protect your API from curl or other servers, so it is not an access control. Real protection is authentication and authorization on every route. If you send cookies cross-origin, set allow_credentials=True, list exact origins, and use fetch with credentials: 'include'.
- Browser to FastAPI: OPTIONS /chat, Origin: localhost:30001OPTIONS /chat, Origin: localhost:3000
- FastAPI to Browser: 204 with Allow-Origin, Allow-Methods, Allow-Headers2204 with Allow-Origin, Allow-Methods, Allow-Headers
- Browser to FastAPI: POST /chat with JSON and Authorization3POST /chat with JSON and Authorization
- FastAPI to Browser: 200 with Access-Control-Allow-Origin4200 with Access-Control-Allow-Origin
Base URLs and the same-origin proxy
Keep the API address in one place. In the browser, the simplest choice is a relative path such as /api, then a Next.js rewrite in next.config.ts forwards /api/:path* to the FastAPI address held in a server-only variable like API_ORIGIN. The browser never sees the backend URL and there is no CORS to configure.
If the browser must call FastAPI directly, read the URL from NEXT_PUBLIC_API_URL. Remember that Next.js copies NEXT_PUBLIC_ values into the JavaScript bundle during next build, so changing the variable later needs a rebuild. Server components and route handlers can read normal environment variables at runtime and call FastAPI over a private network.
- Browser code: relative /api or NEXT_PUBLIC_API_URL
- Server code: API_ORIGIN, read at runtime
- Rewrite: /api/:path* to the FastAPI origin
- No secrets in NEXT_PUBLIC_ variables
Typed requests from OpenAPI
FastAPI builds openapi.json from your Pydantic models and route signatures. The openapi-typescript package turns that file into TypeScript types, and openapi-fetch gives a small typed fetch wrapper that uses them. When a backend field is renamed, regenerating the types makes the TypeScript build fail exactly where the frontend uses the old name.
Give each route a stable operation ID and clear response models so the generated names read well. Regenerate types in CI and fail the build if the committed file differs, so the contract can never drift silently.
Sending authentication safely
Tokens kept in localStorage can be read by any script on the page, so one cross-site scripting bug leaks them. Prefer an HttpOnly, Secure, SameSite=Lax cookie set by your own site. With the same-origin proxy, the cookie goes to Next.js, which can pass it on or swap it for a bearer token when calling FastAPI from the server.
If the browser calls FastAPI directly with a bearer token, keep the token in memory, send it in the Authorization header and refresh it with a short-lived flow. Cookie-based auth across origins also needs CSRF protection for state-changing requests, such as a SameSite cookie plus a CSRF token or an Origin check.
- Same-origin proxy
- HttpOnly cookie to Next.js
- Next.js adds bearer token
- FastAPI validates token
- Direct bearer token
- Token held in memory
- Authorization header
- CORS allows the header
- Avoid
- Tokens in localStorage
- Secrets in NEXT_PUBLIC_
- Tokens in query strings
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Choose CORS or a same-origin proxy~35m
- 2Configure the API base URL~35m
- 3Type requests from OpenAPI~35m
- 4Send authentication safely~35m
- 5Show upload and polling states~35m
Key points
- An origin is scheme, host and port; localhost:3000 and localhost:8000 are different origins.
- With CORS, list exact origins; wildcards are not allowed when credentials are sent.
- NEXT_PUBLIC_ variables are baked into the browser bundle at build time, so never put secrets in them.
- Generate client types from /openapi.json instead of writing them by hand.
- Model every request as idle, loading, success or error, and show each state in the UI.
Key terms
Tap a card to flip it. 0/5 known
Examples
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=['http://localhost:3000', 'https://app.example.com'],
allow_credentials=True,
allow_methods=['GET', 'POST', 'DELETE'],
allow_headers=['Authorization', 'Content-Type'],
)Only needed when the browser calls FastAPI directly from another origin.
Proxying /api to FastAPI with a Next.js rewrite
Step 1: FastAPI runs on port 8000 and Next.js on 3000. Step 2: add a rewrite so the browser calls /api/documents on its own origin. Step 3: set API_ORIGIN=http://localhost:8000 locally and the internal service URL in production. Step 4: open the browser network tab: requests go to localhost:3000/api/..., there are no OPTIONS preflights and no CORS errors. Rollback: remove the rewrite and point the client at NEXT_PUBLIC_API_URL with CORS enabled.
// next.config.ts
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
async rewrites() {
return [
{ source: '/api/:path*', destination: `${process.env.API_ORIGIN}/:path*` },
];
},
};
export default nextConfig;Generating a typed client from openapi.json
Run the generator against the running API, then create a client. The call below is fully typed: the path must exist, the body must match the request model, and data has the response model's shape. If FastAPI renames job_id, the TypeScript build fails at every use.
// npx openapi-typescript http://localhost:8000/openapi.json -o src/api/schema.d.ts
import createClient from 'openapi-fetch';
import type { paths } from './schema';
export const api = createClient<paths>({ baseUrl: '/api' });
const { data, error } = await api.GET('/jobs/{job_id}', {
params: { path: { job_id: jobId } },
});
if (error) showError(error);
else setStatus(data.status);Quick reference
- Origin = scheme + host + port; different ports are different origins.
- CORSMiddleware: list exact origins; no '*' when allow_credentials=True.
- Next.js rewrite: { source: '/api/:path*', destination: API_ORIGIN + '/:path*' }.
- NEXT_PUBLIC_ values are inlined at build time and visible to everyone.
- npx openapi-typescript http://localhost:8000/openapi.json -o schema.d.ts for typed clients.
- Prefer HttpOnly, Secure, SameSite cookies over tokens in localStorage.
- UI states: idle, uploading, queued, processing, ready, failed.
Common mistakes
- Using allow_origins=['*'] with credentials; Starlette then echoes any origin, so every site can call with cookies.
- Putting an API secret in a NEXT_PUBLIC_ variable, where anyone can read it in the bundle.
- Hard-coding http://localhost:8000 in components, which breaks in every other environment.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Start FastAPI on 8000 and Next.js on 3000, call GET /health from a client component and read the exact CORS error in the browser console. Then fix it with CORSMiddleware.
- Exercise 2medium
Replace the CORS setup with a Next.js rewrite and show in the network tab that no preflight requests remain.
- Exercise 3hard
Build an upload component that posts a file, stores the job ID, polls GET /jobs/{id} every two seconds and stops on succeeded or failed, showing a distinct message for each state.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use CORS or a proxy?
- If your frontend is a Next.js app you deploy anyway, a same-origin proxy is simpler and keeps cookies first-party. Use CORS when other sites or a separately hosted frontend must call the API directly.
- Why do I see an OPTIONS request before my POST?
- That is the CORS preflight. The browser sends it for cross-origin requests with JSON bodies or custom headers like Authorization.
- Does CORS stop people from calling my API?
- No. It only limits what browser pages can read. Anyone can still call the API with curl, so every route needs real authentication.
- Can I call FastAPI from a Next.js server component?
- Yes. Server components run on the server, so they can call FastAPI over a private URL with a server-only token and no CORS at all.