On this page

Configuring CORS in FastAPI

Published on August 13, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

A frontend and a backend deployed on different domains, ports, or subdomains look like entirely separate destinations to a browser, and browsers block requests between them by default unless the server explicitly grants permission. CORS is the mechanism for granting that permission correctly — get it right, and a browser-based app can call an API safely from an approved set of origins; get it wrong, either legitimate requests fail with a cryptic console error, or a loosely configured setup ends up granting far more access than intended.


What CORS Actually Protects Against​

CORS is a browser security mechanism, not a server security mechanism. It's enforced exclusively by web browsers and has no effect on direct API calls made from curl, Postman, or any server-to-server communication — those never go through a browser's CORS checks at all.

An origin is the combination of protocol, domain, and port. Two URLs count as different origins if any one of those three differs:

URL AURL BSame origin?http://localhost:3000``http://localhost:8000No — different porthttps://app.mysite.com``https://api.mysite.comNo — different subdomainhttp://mysite.com``https://mysite.comNo — different protocol

When browser-based code running on http://localhost:3000 tries to call http://localhost:8000/api/users, the browser blocks the request unless the server responds with headers explicitly permitting it. Without that configuration, a frontend and backend deployed separately simply fail to talk to each other — and the browser's console error, something like Access-Control-Allow-Origin missing or does not match, is often the first thing a developer encounters the moment frontend and backend are split across different origins for the first time.


How a Preflight Request Works​

For requests using a method other than GET, HEAD, or POST, or carrying a custom header like Authorization, the browser doesn't send the actual request first — it sends a preflight request: an OPTIONS call to the same URL, carrying Origin and Access-Control-Request-Method headers, asking the server whether the real request would be allowed. The server has to respond with the correct Access-Control-Allow-* headers before the browser sends the actual request at all. CORSMiddleware handles this preflight exchange automatically, with no route-specific code needed for it. This is also why a CORS error can appear even for a request that would have succeeded on its own merits — the preflight itself failed, so the real request never got sent in the first place.


Configuring CORSMiddleware​


from fastapi import FastAPI

from fastapi.middleware.cors import CORSMiddleware



app = FastAPI()



origins = [

    "http://localhost:3000",       # Local frontend development server

    "https://www.myapp.com",       # Production frontend

    "https://dashboard.myapp.com"  # Additional production subdomain

]



app.add_middleware(

    CORSMiddleware,

    allow_origins=origins,

    allow_credentials=True,

    allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],

    allow_headers=["Authorization", "Content-Type"],

    max_age=600,  # seconds the browser caches the preflight response

)

Listing origins explicitly, rather than reaching for a wildcard, is what allows allow_credentials=True to work reliably — the section below explains exactly why that combination matters more than it might look.


The Wildcard-and-Credentials Problem​

The CORS specification itself is clear on one point: a response carrying a literal Access-Control-Allow-Origin: * is not valid alongside a request that includes credentials — cookies, an Authorization header, a Bearer token. Browsers enforce this by refusing to expose the response to the calling script when both are present at once, since accepting it would let any website on the internet make authenticated requests to the API on a logged-in user's behalf.

Where this gets genuinely easy to get wrong is assuming FastAPI or Starlette's CORSMiddleware will reject this configuration outright at the server level. It doesn't — setting allow_origins=["*"] together with allow_credentials=True doesn't raise an error, an assertion, or a warning anywhere in the application. Worse, CORSMiddleware actually works around the restriction for credentialed requests specifically: when a request carries credentials and allow_origins is set to ["*"], the middleware reflects the requesting origin back explicitly in the response instead of sending the literal * string, precisely so the request doesn't fail outright. The practical effect is that allow_origins=["*"] combined with allow_credentials=True doesn't reliably behave like "credentials get blocked" — it can end up behaving like "any origin is allowed, with credentials," which is a considerably more permissive outcome than a hard failure would be, and a much easier misconfiguration to miss during testing than an obvious error.


# Ambiguous — no server-side error is raised, but the effective behavior

# for credentialed requests can end up granting access far more broadly

# than "wildcard" suggests

app.add_middleware(

    CORSMiddleware,

    allow_origins=["*"],

    allow_credentials=True,

    allow_methods=["*"],

    allow_headers=["*"],

)



# Correct — explicit origins remove any ambiguity about what's permitted

app.add_middleware(

    CORSMiddleware,

    allow_origins=["https://www.myapp.com"],

    allow_credentials=True,

    allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],

    allow_headers=["Authorization", "Content-Type"],

)

For a genuinely public, credential-free API — a read-only data endpoint, an open feed — a wildcard is fine as long as allow_credentials stays False:


# Correct for a public, credential-free API

app.add_middleware(

    CORSMiddleware,

    allow_origins=["*"],

    allow_credentials=False,  # must stay False alongside wildcard origins

    allow_methods=["GET"],

    allow_headers=["*"],

)

The dividing line isn't whether the configuration technically runs without error — it's whether the API issues cookies or expects an Authorization header at all. If it does, explicit origins are the only configuration that behaves predictably.


Matching Dynamic Subdomains with allow_origin_regex​

When an API needs to accept requests from a set of origins that isn't fixed in advance — preview deployment URLs, tenant-specific subdomains — allow_origin_regex replaces the static list:


app.add_middleware(

    CORSMiddleware,

    allow_origin_regex=r"https://.*\.myapp\.com",  # any subdomain of myapp.com

    allow_credentials=True,

    allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],

    allow_headers=["Authorization", "Content-Type"],

)

allow_origin_regex takes a Python regular expression, evaluated against the complete origin string, protocol and port included — a pattern that only accounts for the domain portion will fail to match origins that differ in scheme or port even when the domain itself is correct.


CORSMiddleware Parameter Reference​

ParameterTypeDefaultDescriptionallow_origins``list[str]``()Explicit list of allowed originsallow_origin_regex``str``NoneRegex matching allowed originsallow_credentials``bool``FalseAllow cookies and Authorization headersallow_methods``list[str]``("GET",)Allowed HTTP methodsallow_headers``list[str]``()Allowed request headersexpose_headers``list[str]``()Response headers exposed to the browsermax_age``int``600Preflight cache duration, in seconds

Key Takeaways​

CORS is enforced entirely by browsers, never by direct server-to-server or command-line requests, and it exists to control which browser-based origins can call an API rather than to restrict the API itself. A preflight OPTIONS request precedes any non-simple request, and CORSMiddleware handles that exchange automatically once allow_origins, allow_methods, and allow_headers are configured. The wildcard-and-credentials combination is the single most consequential detail here: it isn't blocked at the server level by an exception or assertion, and CORSMiddleware's own behavior of reflecting the request's origin for credentialed calls means a wildcard can end up functioning as "allow any origin with credentials" rather than failing safely — which is exactly why listing real, explicit origins is the only configuration that behaves predictably for any API that issues cookies or expects an Authorization header.

Frequently Asked Questions​

My API works fine in Postman but fails when called from my frontend. Why?

CORS is enforced exclusively by browsers — Postman, curl, and server-to-server calls never go through a CORS check at all, so they succeed regardless of the server's CORS configuration. A frontend running in a browser is the only client type that actually triggers CORS enforcement, which is why the same request can behave completely differently depending on where it's sent from.

Why does my browser console show a CORS error even though the endpoint works when I test it directly?

For requests using a method other than GET, HEAD, or POST, or carrying a header like Authorization, the browser sends a preflight OPTIONS request first and only sends the real request if that preflight succeeds. If the preflight fails, the actual request never goes out — the endpoint itself may work perfectly, but the browser never gets far enough to call it.

I set allow_origins=["*"] and allow_credentials=True and nothing raised an error. Is my configuration safe?

No — and the absence of an error is exactly the trap. Starlette's CORSMiddleware doesn't reject this combination at the server level. For credentialed requests specifically, it reflects the actual requesting origin back instead of sending a literal wildcard, which means this configuration can end up allowing any origin to make authenticated requests rather than failing safely. Listing explicit origins is the only way to avoid this ambiguity.

Why does my request still fail even though I added the correct origin to allow_origins?

Check that the origin matches exactly, including protocol and port — http://localhost:3000 and https://localhost:3000 are different origins, as are localhost:3000 and localhost:5173. A single mismatched character anywhere in the origin string means the entry in allow_origins won't match the browser's actual Origin header.

Should I just set allow_methods and allow_headers to "*" to avoid configuration issues?

It depends entirely on allow_credentials. With allow_credentials=False on a genuinely public, credential-free API, wildcards for methods and headers are fine. The moment the API issues cookies or expects an Authorization header, explicit origins, methods, and headers are the safer choice, since a wildcard's actual behavior under those conditions is inconsistent with what "wildcard" usually implies.

How do I allow requests from any subdomain of my domain without listing every one individually?

Use allow_origin_regex instead of allow_origins — a regex like r"https://.*.myapp.com" matches any subdomain of myapp.com. Remember it's evaluated against the full origin string, protocol included, so the pattern needs to account for the scheme and not just the domain portion.

Do I need to add OPTIONS to allow_methods manually?

No — CORSMiddleware handles the OPTIONS preflight request automatically and responds to it before your route code ever runs. Listing OPTIONS in allow_methods documents that it's permitted, but the middleware doesn't require a route handler to exist for OPTIONS requests specifically.

Why does changing max_age matter if CORS still works without setting it?

max_age controls how long a browser caches a successful preflight response before sending another one. Without it, the default still applies, but a shorter value means the browser re-sends a preflight OPTIONS request more often, and a longer value reduces that overhead at the cost of the browser taking longer to notice a CORS configuration change on the server.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

API Security Best Practices

Next

HTTPS