CORS & Preflight Simulator · Python FastAPI + Next.js

FastAPI + Next.js CORS Config Simulator & Fix Guide

Simulate Fetch Standard preflight (OPTIONS) triggers, credential rules, and origin matching between Next.js 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 (Next.js)

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:3000",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
    allow_headers=["Content-Type", "Authorization"],
    max_age=86400,
)

Preflight (OPTIONS)

Triggered · Passed

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.

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:3000', 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:3000
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
Actual Response (POST)
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Credentials: true
Vary: Origin

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

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:

DevTools Console Output

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.

  1. 1Register CORSMiddleware Last With Explicit Next.js Origins

    app/main.py

    Add 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.pypython
    import 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,
    )
  2. 2Eliminate 307 Trailing-Slash Preflight Redirects on APIRouters

    app/routers/documents.py

    Match 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.pypython
    from 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}
  3. 3Preserve CORS Headers on Unhandled 500 Exceptions

    app/main.py

    Because 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.pypython
    from 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,
        )
  4. 4Send Clean Cross-Origin Requests From Next.js Client Components

    src/lib/fastapi.ts

    Match 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.tstypescript
    const 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.

Pitfall 1

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.

Pitfall 2

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.

Pitfall 3

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.

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