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. Useallow_origin_regexfor preview deployments. allow_credentials=Truedoes not belong withallow_origins=["*"]. List origins explicitly.- Add
CORSMiddlewarelast 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
OPTIONSthemselves. - Test with
curl -i -X OPTIONSbefore 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.
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.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.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:
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
Authorizationheader (Bearer tokens) PUT,PATCHorDELETE- 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.
Two details trip people up:
- The preflight never carries credentials: no cookies, no
Authorizationheader. If anything in front of your routes requires auth onOPTIONS, the preflight gets a 401 and fails. - If the preflight fails, the real request is never sent. Your server logs show an
OPTIONSand 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:
# 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:
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"}ALLOWED_ORIGINS="https://app.example.com,https://www.example.com" uvicorn main:appA few notes on the options:
allow_methodsdefaults toGETonly in Starlette. If yourPOSTpreflight fails, this is a likely reason.["*"]is fine here.allow_headersmust includeAuthorizationif you send Bearer tokens. The simple headers (Accept,Accept-Language,Content-Language,Content-Type) are always allowed.expose_headerscontrols which response headers your JavaScript can read. Without it,response.headers.get("X-Total-Count")returnsnulleven though the header is on the wire.allow_origin_regexis checked in addition toallow_origins. Keep it tight; a loose pattern like.*\.vercel\.appallows 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.
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.
How to tell:
- Open DevTools, Network tab, click the failed request. If the status column shows 500 (not "CORS error" on the
OPTIONSrow), 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:
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:
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://tohttps://, or the apex domain towww, 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:
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# 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:
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:
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:
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:
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:
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
OKHeader 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 see | Likely cause |
|---|---|
400 with body Disallowed CORS origin | Origin not in allow_origins (trailing slash, scheme, www) |
400 with Disallowed CORS method or headers | Add the method or header to the middleware config |
401 or 403 | Auth middleware runs before CORS, or the proxy requires auth |
301, 307 or 308 | A redirect in the proxy, platform or app |
204 with no CORS headers | Proxy is answering OPTIONS itself |
Two access-control-allow-origin lines | Both proxy and app are adding headers |
Then test the real request with the Origin header to catch 500s:
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:
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
async rewrites() {
return [
{
source: "/api/:path*",
destination: `${process.env.API_ORIGIN}/:path*`,
},
];
},
};
module.exports = nextConfig;// 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_originslists the exact production origin:https://, correct host, no trailing slash.- Preview URLs are covered by a tight
allow_origin_regex. - No
"*"inallow_originswhenallow_credentials=True. allow_methodsandallow_headersinclude what the frontend sends (Authorization!).CORSMiddlewareis 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.