Typical Browser Console Error (Next.js → Python FastAPI)
When cross-origin headers are missing, mismatched, or blocked during preflight between Next.js and Python FastAPI, Chrome and Firefox log an error matching the pattern below in DevTools:
Access to fetch at 'http://localhost:8000/api/v1/documents' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
Why CORS Blocks Requests Between Next.js and Python FastAPI
Connecting a Next.js App Router frontend on http://localhost:3000 to a Python FastAPI backend powered by Uvicorn on http://localhost:8000 is one of the most widely adopted modern AI and data-intensive SaaS architectures. Because Starlette (the underlying ASGI toolkit powering FastAPI) emits zero CORS headers out of the box, every browser-side fetch call from Next.js Client Components is immediately blocked until CORSMiddleware is configured and positioned accurately.
Beyond basic origin whitelisting, FastAPI introduces two distinctive CORS failure modes that routinely catch experienced full-stack engineers off guard. First, FastAPI automatically issues HTTP 307 Temporary Redirects when a route is declared with a trailing slash (such as @router.post("/")) on a prefixed APIRouter and Next.js fetches /api/v1/documents without a trailing slash. Under the Fetch Standard, browsers strictly forbid HTTP redirects on OPTIONS preflight requests and abort immediately with "Redirect is not allowed for a preflight request."
Second, Starlette executes middleware in reverse registration order (last-in, first-out) and handles unhandled Python exceptions inside ServerErrorMiddleware outside CORSMiddleware. If an uncaught runtime exception triggers an HTTP 500 Internal Server Error before CORSMiddleware wraps the response, Next.js receives a bare 500 response with zero Access-Control-Allow-Origin headers, disguising a backend Python traceback as a browser CORS error.
In production deployments where FastAPI runs behind Gunicorn, Uvicorn workers, Docker, or a managed platform like Render or Railway, always run an automated curl preflight smoke test against the live HTTPS endpoint before pointing Next.js production traffic to it. Confirm that OPTIONS returns HTTP 200 or 204, never a 307 trailing-slash redirect or 405 Method Not Allowed, and verify that your FastAPI error logs do not swallow startup tracebacks that strip CORSMiddleware headers on HTTP 500 responses. Keeping CORS origins strictly driven by environment variables also lets staging and production Next.js deployments share identical Docker images safely.
Step-by-Step Python FastAPI + Next.js CORS Fix Guide
Follow each step below in order to eliminate preflight failures and lock down production origins safely for Python FastAPI.
1Register CORSMiddleware Last With Explicit Next.js Origins
app/main.pyAdd CORSMiddleware to your FastAPI application using explicit origins loaded from environment variables and stripped of trailing slashes. Because Starlette wraps middleware like an onion, executing the last-registered middleware first, always add CORSMiddleware AFTER custom authentication, logging, or rate-limiting middleware so early 401/429 responses still carry valid CORS headers.
app/main.pypythonimport os from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI(title="OpsCheck API") allowed_origins = [ origin.strip().rstrip("/") for origin in os.getenv("CORS_ORIGINS", "http://localhost:3000").split(",") if origin.strip() ] # Register custom middleware first, then CORSMiddleware last as the outermost wrapper app.add_middleware( CORSMiddleware, allow_origins=allowed_origins, allow_credentials=True, allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], allow_headers=["Content-Type", "Authorization"], max_age=86400, )2Eliminate 307 Trailing-Slash Preflight Redirects on APIRouters
app/routers/documents.pyMatch the exact URL convention your Next.js client calls. When mounting an APIRouter with prefix="/api/v1/documents", declare the collection endpoint as "" instead of "/" (or instantiate FastAPI with redirect_slashes=False) so OPTIONS /api/v1/documents returns 200 OK instead of a forbidden 307 redirect.
app/routers/documents.pypythonfrom fastapi import APIRouter from pydantic import BaseModel router = APIRouter(prefix="/api/v1/documents", tags=["documents"]) class DocumentIn(BaseModel): title: str content: str # Use "" instead of "/" so POST /api/v1/documents does not 307-redirect @router.post("") async def create_document(payload: DocumentIn): return {"status": "created", "title": payload.title}3Preserve CORS Headers on Unhandled 500 Exceptions
app/main.pyBecause Starlette's ServerErrorMiddleware sits outside CORSMiddleware, uncaught exceptions return 500 responses lacking Access-Control-Allow-Origin. Register a global exception handler that checks the request Origin against your allowlist and returns a clean JSONResponse with CORS headers so browsers surface the real 500 error instead of a generic CORS block.
app/main.pypythonfrom fastapi import Request from fastapi.responses import JSONResponse @app.exception_handler(Exception) async def unhandled_exception_handler(request: Request, exc: Exception): origin = request.headers.get("origin") headers = {} if origin and origin in allowed_origins: headers["Access-Control-Allow-Origin"] = origin headers["Access-Control-Allow-Credentials"] = "true" headers["Vary"] = "Origin" return JSONResponse( status_code=500, content={"detail": "Internal server error"}, headers=headers, )4Send Clean Cross-Origin Requests From Next.js Client Components
src/lib/fastapi.tsMatch the exact FastAPI route path without trailing-slash drift, send Authorization and Content-Type explicitly, and include credentials: "include" only when FastAPI sets or reads HttpOnly authentication cookies.
src/lib/fastapi.tstypescriptconst FASTAPI_URL = process.env.NEXT_PUBLIC_FASTAPI_URL ?? 'http://localhost:8000'; export async function createDocument(token: string, title: string, content: string) { const res = await fetch(`${FASTAPI_URL}/api/v1/documents`, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}`, }, body: JSON.stringify({ title, content }), }); if (!res.ok) { const err = await res.json().catch(() => ({ detail: res.statusText })); throw new Error(err.detail ?? 'FastAPI request failed'); } return res.json(); }
Common Python FastAPI + Next.js 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.
Starlette Middleware LIFO Ordering Traps
In FastAPI and Starlette, app.add_middleware() wraps the application like concentric layers: the LAST middleware registered executes FIRST on incoming requests and LAST on outgoing responses. If you register an auth or API-key middleware after CORSMiddleware and it short-circuits with 401 or 403, CORSMiddleware never sees the response and Next.js reports a CORS failure.
307 Temporary Redirects Caused by Trailing Slashes on APIRouter
Declaring @router.post("/") on a router with prefix="/api/v1/documents" causes FastAPI to redirect /api/v1/documents to /api/v1/documents/ via HTTP 307. While curl or Swagger UI follows redirects cleanly, browsers reject any 3xx redirect during an OPTIONS preflight check.
Using allow_origins=["*"] Together With allow_credentials=True
Passing both allow_origins=["*"] and allow_credentials=True violates the Fetch Standard intent and either fails browser credential checks or silently echoes arbitrary origins in ways that fail security audits. Always specify explicit origins whenever allow_credentials=True.
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 FastAPI return "Redirect is not allowed for a preflight request" in Chrome?
- Your Next.js client is requesting a URL without a trailing slash (e.g., /api/v1/documents) while your FastAPI route is defined with a trailing slash (/api/v1/documents/). FastAPI responds to the OPTIONS preflight with a 307 redirect, which the browser Fetch specification forbids. Change the router path to "" or match the trailing slash identically on both sides.
- Does FastAPI allow_headers=["*"] cover the Authorization header?
- Starlette reflects requested headers when allow_headers=["*"] is set, which can mask the issue locally, but per the Fetch Standard a literal Access-Control-Allow-Headers: * header never authorizes Authorization or credentialed requests. Listing ["Content-Type", "Authorization"] explicitly guarantees consistent behavior across proxies, gateways, and browsers.
- Should I put CORSMiddleware before or after custom Starlette BaseHTTPMiddleware?
- Call app.add_middleware(CORSMiddleware, ..) AFTER your other app.add_middleware(..) calls. Because Starlette wraps middleware in reverse order, adding CORSMiddleware last ensures it is the outermost layer and answers OPTIONS preflights before auth middleware can reject them.
- How do I allow Next.js preview deployments on Vercel in FastAPI?
- Pass allow_origin_regex=r"^https://my-nextjs-app-[a-z0-9-]+\.vercel\.app$" to CORSMiddleware alongside your static allow_origins list. Always anchor the regex with ^ and $ and escape literal dots so malicious third-party domains cannot match your preview rule.
Related CORS Stack Simulators
Browse all 12 stacks →FastAPI + React (Vite) CORS Config Simulator & Fix Guide
Simulate and resolve CORS errors between Python FastAPI and React Vite on port 5173. Fix preflight OPTIONS failures, Pydantic 422 responses, and upload headers.
Laravel API + Next.js App Router CORS Simulator & Fix Guide
Debug CORS between Laravel 11/12 APIs and Next.js App Router on port 3000. Separate Server Component fetches from Client Component browser preflights.
Node.js Express + Next.js App Router CORS Simulator & Fix Guide
Fix CORS preflight and cookie credential errors between Node.js Express APIs and Next.js App Router. Configure cors() middleware, app.options, and Helmet.
Nginx Reverse Proxy + Docker API CORS Simulator & Fix Guide
Fix Nginx reverse proxy CORS bugs for Docker APIs. Prevent duplicate Access-Control-Allow-Origin headers, add always on 4xx/5xx errors, and handle OPTIONS 204.