All articles
FastAPIPythonCORSDeployment

FastAPI CORS Works on Localhost but Fails in Production

Your FastAPI API works locally but the deployed frontend gets CORS errors. Here's why it happens and how to fix origins, proxies, redirects and cookies.

Tushar Pachouri14 min read

Everything works on localhost:3000 talking to localhost:8000. You deploy the Next.js frontend to Vercel and the FastAPI backend to a VPS or a container platform, and every request dies with a red CORS error in the console. The error message points at headers, but the real cause is often a typo in an origin, a proxy, a redirect or a 500 that has nothing to do with CORS.

This post walks through what the browser is actually checking, the exact error messages you'll see, and the fixes I reach for, in the order I check them.

TL;DR

  • Put the exact frontend origin in allow_origins: scheme + host + port, no trailing slash. Use allow_origin_regex for preview deployments.
  • allow_credentials=True does not belong with allow_origins=["*"]. List origins explicitly.
  • Add CORSMiddleware last so it wraps everything. Unhandled 500s still come back without CORS headers, which makes server bugs look like CORS bugs.
  • Only one layer should set CORS headers. Proxies, CDNs and API gateways can strip them, duplicate them, or answer OPTIONS themselves.
  • Test with curl -i -X OPTIONS before touching code. If you'd rather avoid CORS entirely, proxy the API through Next.js rewrites.

The symptom

You'll see one of these in the browser console. The wording is from Chromium-based browsers; Firefox says the same things differently.

Text
Access to fetch at 'https://api.example.com/items' from origin 'https://app.example.com'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on
the requested resource.
Text
Access to fetch at 'https://api.example.com/items' from origin 'https://app.example.com'
has been blocked by CORS policy: Response to preflight request doesn't pass access
control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Text
Access to fetch at 'https://api.example.com/me' from origin 'https://app.example.com'
has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in
the response must not be the wildcard '*' when the request's credentials mode is 'include'.

And a few variants worth recognising, because each one points at a different cause:

Text
Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
The 'Access-Control-Allow-Origin' header contains multiple values 'https://app.example.com, *', but only one is allowed.

Why it happens

CORS is enforced by the browser, not by your server. The server only sends headers; the browser decides whether your JavaScript is allowed to read the response. That's why curl and Postman always "work": they don't check anything.

Simple vs preflighted requests

A request is simple if it is GET, HEAD or POST, uses only CORS-safelisted headers, and (for POST) has a Content-Type of text/plain, multipart/form-data or application/x-www-form-urlencoded. The browser sends it directly and checks the response for Access-Control-Allow-Origin.

Almost every real API call is not simple. Any of these triggers a preflight:

  • Content-Type: application/json
  • An Authorization header (Bearer tokens)
  • PUT, PATCH or DELETE
  • Custom headers like X-Request-ID

For those, the browser first sends an OPTIONS request with Origin, Access-Control-Request-Method and Access-Control-Request-Headers. The server must answer with a 2xx status, no redirect, and headers that allow that origin, method and headers. Only then does the real request go out.

A preflighted request: the OPTIONS check must pass before the real request is sent.

Two details trip people up:

  1. The preflight never carries credentials: no cookies, no Authorization header. If anything in front of your routes requires auth on OPTIONS, the preflight gets a 401 and fails.
  2. If the preflight fails, the real request is never sent. Your server logs show an OPTIONS and nothing else.

Why localhost hides the problem

Locally you usually have one origin (http://localhost:3000), no reverse proxy, no TLS, no CDN, and often a dev proxy that makes requests same-origin anyway. Production adds HTTPS, a real domain (maybe with and without www), preview URLs, a load balancer, and sometimes a gateway that has its own opinions about CORS. Each one is a new way to break the headers.

Fixes

1. Configure CORSMiddleware with exact origins

The browser compares the Origin header as a string against what your server sends back. https://app.example.com/ (trailing slash), http://app.example.com (wrong scheme) and https://www.app.example.com are all different origins.

Here's the broken version I see most often:

Python
# Broken: trailing slash, wildcard with credentials, default methods
app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com/", "*"],
    allow_credentials=True,
)

And a working setup that reads origins from an environment variable and normalises them:

Python
import os

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()


def load_origins() -> list[str]:
    raw = os.getenv("ALLOWED_ORIGINS", "http://localhost:3000")
    # Strip spaces and trailing slashes; an origin never has a path.
    return [o.strip().rstrip("/") for o in raw.split(",") if o.strip()]


app.add_middleware(
    CORSMiddleware,
    allow_origins=load_origins(),
    # Vercel preview deployments: https://my-app-<hash>-my-team.vercel.app
    allow_origin_regex=r"^https://my-app-[a-z0-9-]+-my-team\.vercel\.app$",
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
    allow_headers=["Authorization", "Content-Type", "X-Request-ID"],
    expose_headers=["Content-Disposition", "X-Total-Count"],
    max_age=600,
)


@app.get("/health")
async def health() -> dict[str, str]:
    return {"status": "ok"}
Terminal
ALLOWED_ORIGINS="https://app.example.com,https://www.example.com" uvicorn main:app

A few notes on the options:

  • allow_methods defaults to GET only in Starlette. If your POST preflight fails, this is a likely reason. ["*"] is fine here.
  • allow_headers must include Authorization if you send Bearer tokens. The simple headers (Accept, Accept-Language, Content-Language, Content-Type) are always allowed.
  • expose_headers controls which response headers your JavaScript can read. Without it, response.headers.get("X-Total-Count") returns null even though the header is on the wire.
  • allow_origin_regex is checked in addition to allow_origins. Keep it tight; a loose pattern like .*\.vercel\.app allows every Vercel project on the internet.

Warning: The CORS spec doesn't allow Access-Control-Allow-Origin: * together with credentials. Depending on the request and the Starlette version, the middleware may echo the origin in some cases and send * in others, which gives you intermittent failures. When it does echo the origin, you've told the browser that any site may make credentialed requests to your API. List your origins explicitly.

2. Get the middleware order right

In Starlette, the middleware you add last is the outermost. You want CORSMiddleware on the outside so that it answers preflights before anything else sees them, and adds headers to every response that comes back through it.

Python
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

app = FastAPI()


@app.middleware("http")
async def require_api_key(request: Request, call_next):
    # Runs INSIDE CORS because CORSMiddleware is added after it.
    if request.url.path.startswith("/admin") and request.headers.get("x-api-key") != "expected":
        return JSONResponse({"detail": "Forbidden"}, status_code=403)
    return await call_next(request)


# Added last = outermost. Preflights are answered here and never reach the auth check.
app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

If you flip that order, the auth middleware sees the preflight first, finds no API key (preflights never have one), returns 403 without CORS headers, and the browser reports "Response to preflight request doesn't pass access control check".

3. Stop 500s from looking like CORS errors

This is the one that wastes the most time. FastAPI's HTTPException, validation errors (422) and 404s are handled inside the middleware stack, so they get CORS headers. But an unhandled exception bubbles past CORSMiddleware to Starlette's outermost ServerErrorMiddleware, which returns a plain 500 without CORS headers. The browser can't read it, so it reports a missing Access-Control-Allow-Origin header.

ServerErrorMiddleware (outermost) CORSMiddleware (added last) Your @app.middleware functions Exception handlers and routes HTTPException, 422 or 404 unhandled exception (a bug) Handled error response passes back through CORSMiddleware CORS headers added Unhandled exception bubbles past CORS to a plain 500 from the outer layer no CORS headers
Handled errors return through CORSMiddleware; unhandled ones become a bare 500 outside it.

How to tell:

  • Open DevTools, Network tab, click the failed request. If the status column shows 500 (not "CORS error" on the OPTIONS row), the preflight passed and your handler crashed.
  • Check the server logs for a traceback at the same timestamp.
  • Replay the request with curl (see below). If you get a 500, it's a bug, not a CORS config problem.

To keep CORS headers on crash responses, catch exceptions in a middleware that sits inside CORS:

Python
import logging

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

logger = logging.getLogger("app")
app = FastAPI()


@app.middleware("http")
async def catch_unhandled_errors(request: Request, call_next):
    try:
        return await call_next(request)
    except Exception:
        logger.exception("Unhandled error on %s %s", request.method, request.url.path)
        return JSONResponse({"detail": "Internal Server Error"}, status_code=500)


app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

Now the frontend sees a real 500 with a JSON body, which is far easier to debug than a fake CORS error.

4. Check what your proxy is doing

In production there is usually something between the browser and Uvicorn: Nginx, Caddy, a load balancer, Cloudflare, or an API gateway. Each can break CORS in its own way.

Duplicate headers. If Nginx adds Access-Control-Allow-Origin and FastAPI adds it, the response carries two values and the browser rejects it with "contains multiple values ... but only one is allowed". Pick one owner. I let the app own CORS and keep the proxy dumb:

Diff
 location / {
     proxy_pass http://127.0.0.1:8000;
     proxy_set_header Host $host;
     proxy_set_header X-Forwarded-Proto $scheme;
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
-    add_header Access-Control-Allow-Origin * always;
-    if ($request_method = OPTIONS) {
-        return 204;
-    }
 }

That if ($request_method = OPTIONS) { return 204; } block is a common copy-paste. It answers every preflight at the proxy, often with no CORS headers, so your app never gets a chance.

If you do want Nginx to own CORS, remember that add_header only applies to 2xx and 3xx responses unless you add always. Without it, every 4xx and 5xx comes back without CORS headers.

API gateways. Managed gateways (AWS API Gateway, for example) can be configured to handle CORS themselves. When they are, they answer the preflight and may ignore or override the headers your backend returns. Configure CORS in exactly one place.

CDN caching. When your app echoes a specific origin, Starlette also sends Vary: Origin. Many CDNs, Cloudflare included, don't fully honor Vary for cache keys, so a cached response with Access-Control-Allow-Origin: https://app.example.com can be served to https://www.example.com. Bypass the cache for API routes, or at least for anything that varies by origin.

5. Watch for redirects

A preflight that gets a 301, 302, 307 or 308 fails with "Redirect is not allowed for a preflight request". Common sources in production:

  • The platform or proxy redirects http:// to https://, or the apex domain to www, and your frontend uses the non-canonical URL.
  • A host-level rule adds or removes trailing slashes.

FastAPI itself redirects /items to /items/ with a 307 when the route is declared with a trailing slash. CORSMiddleware answers the preflight before routing, so the preflight is fine, but the real request then gets a 307. Behind a TLS-terminating proxy, Uvicorn may build that redirect URL with http://, because it doesn't trust the proxy's X-Forwarded-Proto unless told to. The browser then blocks it as mixed content.

Fix it on both sides:

Python
from fastapi import FastAPI

# Option A: be consistent and call the exact path the route declares.
# Option B: turn off the automatic slash redirect.
app = FastAPI(redirect_slashes=False)


@app.post("/items")
async def create_item(item: dict) -> dict:
    return item
Terminal
# Trust X-Forwarded-Proto from your proxy so generated URLs use https.
# Replace the IP with your proxy's address; "*" trusts every client.
uvicorn main:app --host 0.0.0.0 --port 8000 --proxy-headers --forwarded-allow-ips="10.0.0.5"

6. Don't mix HTTP and HTTPS

If your frontend is on https:// and your API URL is http://, the browser blocks the request before CORS even comes into play:

Text
Mixed Content: The page at 'https://app.example.com/' was loaded over HTTPS, but requested
an insecure resource 'http://api.example.com/items'. This request has been blocked; the
content must be served over HTTPS.

Check the environment variable your frontend uses for the API base URL. On Vercel, NEXT_PUBLIC_* variables are inlined at build time, so changing the value means redeploying.

7. Cookies need credentials on both sides

If you use cookie sessions instead of Bearer tokens, three things must line up.

The frontend has to opt in to sending cookies:

TypeScript
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/me`, {
  method: "GET",
  credentials: "include",
});

The API must allow credentials (allow_credentials=True, explicit origins) and set the cookie so the browser will send it cross-site:

Python
from fastapi import FastAPI, Response

app = FastAPI()


@app.post("/login")
async def login(response: Response) -> dict[str, bool]:
    token = "replace-with-a-real-session-token"
    response.set_cookie(
        key="session",
        value=token,
        httponly=True,
        secure=True,       # required when SameSite=None
        samesite="none",   # allow the cookie on cross-site requests
        max_age=60 * 60 * 24 * 7,
    )
    return {"ok": True}

Third, accept that browsers increasingly restrict third-party cookies. If your app is on my-app.vercel.app and your API is on my-api.onrender.com, those are different sites, and some browsers will block the cookie no matter what headers you send. Putting both on the same registrable domain (app.example.com and api.example.com) or using the proxy approach below avoids this.

Debug with curl first

Before changing any code, ask the server what it actually returns. This simulates the browser's preflight:

Terminal
curl -i -X OPTIONS https://api.example.com/items \
  -H "Origin: https://app.example.com" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: content-type, authorization"

A healthy response looks like this:

Text
HTTP/1.1 200 OK
vary: Origin
access-control-allow-methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
access-control-max-age: 600
access-control-allow-headers: Accept, Accept-Language, Authorization, Content-Language, Content-Type, X-Request-ID
access-control-allow-credentials: true
access-control-allow-origin: https://app.example.com
content-type: text/plain; charset=utf-8

OK

Header order and casing vary by server and proxy; what matters is that each header is present, appears once, and matches what the browser asked for.

How to read what you get back:

What you seeLikely cause
400 with body Disallowed CORS originOrigin not in allow_origins (trailing slash, scheme, www)
400 with Disallowed CORS method or headersAdd the method or header to the middleware config
401 or 403Auth middleware runs before CORS, or the proxy requires auth
301, 307 or 308A redirect in the proxy, platform or app
204 with no CORS headersProxy is answering OPTIONS itself
Two access-control-allow-origin linesBoth proxy and app are adding headers

Then test the real request with the Origin header to catch 500s:

Terminal
curl -i -X POST https://api.example.com/items \
  -H "Origin: https://app.example.com" \
  -H "Content-Type: application/json" \
  -d '{"name": "test"}'

Tip: In DevTools, right-click the failed request and choose Copy as cURL. You get the exact headers the browser sent, which removes guesswork.

The alternative: avoid CORS with Next.js rewrites

If the frontend is Next.js, you can make API calls same-origin and skip CORS completely. The browser calls /api/... on your own domain, and Next.js forwards the request to FastAPI server-side:

CROSS-ORIGIN: THE BROWSER CALLS THE API Browser app.example.com FastAPI api.example.com OPTIONS preflight, then POST needs CORS headers on every response SAME ORIGIN: NEXT.JS REWRITES FORWARD THE CALL Browser fetch("/api/items") Next.js server app.example.com/api FastAPI API_ORIGIN same origin server side No preflight, no CORS headers, first-party cookies
With rewrites the browser only talks to its own origin and Next.js forwards the call.
JavaScript
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  async rewrites() {
    return [
      {
        source: "/api/:path*",
        destination: `${process.env.API_ORIGIN}/:path*`,
      },
    ];
  },
};

module.exports = nextConfig;
TypeScript
// In the browser: same origin, so no preflight and no CORS headers needed.
const res = await fetch("/api/items", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "test" }),
});

Cookies set by the API now belong to your app's domain, so they're first-party. The trade-offs: an extra network hop, your Next.js host's request limits and timeouts apply, and API_ORIGIN is read when the config loads, so set it in your hosting environment before building. Don't name the route prefix /api if you already use Next.js API routes or route handlers there; pick something like /backend.

Checklist

  • allow_origins lists the exact production origin: https://, correct host, no trailing slash.
  • Preview URLs are covered by a tight allow_origin_regex.
  • No "*" in allow_origins when allow_credentials=True.
  • allow_methods and allow_headers include what the frontend sends (Authorization!).
  • CORSMiddleware is added last, after auth and other custom middleware.
  • Unhandled exceptions are caught inside CORS so 500s keep their headers.
  • Exactly one layer (app, proxy or gateway) sets CORS headers.
  • The preflight URL returns 200 with no redirects (curl -i -X OPTIONS).
  • Uvicorn trusts the proxy's forwarded headers so redirects stay on https.
  • Frontend uses https:// for the API URL.
  • Cookie auth: credentials: "include", SameSite=None; Secure, and ideally same-site domains.

Wrap-up

"CORS error" in the console is the browser telling you it couldn't read a response. It's not always telling you why. Start with curl and the Network tab to find out whether the preflight failed, the real request crashed, or something in between rewrote the response. Most production CORS bugs come down to an origin string that's off by one character, a proxy doing CORS on its own, or a 500 hiding behind a missing header. Fix the one layer that's wrong, and keep CORS owned in exactly one place.

Stuck on something like this?

I build and fix full-stack products for startups and indie founders. Tell me what's broken.

Get in touch