A browser treats scheme, hostname and port as part of an origin. A frontend on one origin may need explicit CORS permission to call a FastAPI backend on another.
IN THIS ARTICLE
Check access and requirements
List the real production and approved staging frontend origins. Determine whether requests use cookies or other credentials and which methods and headers are necessary.
01 Set FastAPI CORS for a separate website origin
Configure
CORSMiddlewarewith the specific permitted origins. Use exact origins, including the scheme and non-default port where relevant.Allow only the methods and request headers the frontend needs. If credentialed requests are enabled, use explicit settings rather than wildcard origins, methods or headers.
Keep authentication and authorization in the API. CORS controls browser access behavior and does not verify that a caller is entitled to perform an operation.
Test the browser preflight request and the following API request. Include the same credentials mode the production frontend uses.
Review error responses and proxy behavior so required CORS headers are not lost on a failure or redirect.
02 Example: allow one credentialed FastAPI frontend
For an API used by the specific HTTPS website shown below, merge this middleware configuration into the existing application. The explicit lists describe the origins, methods and headers needed by that frontend. Add another origin only after verifying its ownership and purpose.
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=['https://www.example.com'],
allow_credentials=True,
allow_methods=['GET', 'POST'],
allow_headers=['Authorization', 'Content-Type'],
)
Keep route authentication, authorisation and any required CSRF protection. Cookie domain and SameSite settings must also fit the deployment. If the frontend never uses cookies, review whether credentialed CORS is needed at all. An allowed origin is not permission to read another account’s data.
Expected result: The browser’s preflight and approved request both succeed. A request from an unapproved browser origin is not granted credentialed access, while an unauthorised user still fails the API’s own permission checks.
Confirm the expected result
Confirm the approved frontend can perform the intended request and an unapproved browser origin cannot read a protected response. Verify cookies also meet their domain and SameSite requirements.
Resolve setup problems
If a request works in a server-side client but fails in a browser, inspect the preflight and response headers. That difference does not prove the API credentials or database are wrong.
A common question
Can I solve CORS by allowing every origin with credentials?
Use specific allowed origins for credentialed browser access. Broad settings can expose protected interactions and may be rejected by the browser’s CORS rules.