0
0
FastapiDebug / FixBeginner · 4 min read

How to Fix CORS Error in FastAPI Quickly and Easily

To fix a CORS error in FastAPI, add the CORSMiddleware from fastapi.middleware.cors and configure allowed origins. This middleware enables your API to accept requests from different domains, preventing the browser from blocking them.
🔍

Why This Happens

CORS (Cross-Origin Resource Sharing) errors happen because browsers block web pages from making requests to a different domain than the one that served the page. This is a security feature to prevent malicious sites from accessing your API without permission.

If your FastAPI app does not explicitly allow other domains, the browser will block the request and show a CORS error.

python
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}
Output
Access to fetch at 'http://your-api-domain/' from origin 'http://your-frontend-domain' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
🔧

The Fix

You fix this by adding CORSMiddleware to your FastAPI app. This middleware lets you specify which origins (domains) can access your API. You can allow specific domains or all domains during development.

This change tells the browser it is safe to allow requests from those origins.

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

app = FastAPI()

origins = [
    "http://localhost",
    "http://localhost:3000",
    "https://your-frontend-domain.com"
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"]
)

@app.get("/")
async def root():
    return {"message": "Hello World"}
Output
API responds normally and browser allows cross-origin requests without CORS errors.
🛡️

Prevention

To avoid CORS errors in the future, always configure CORSMiddleware when your API will be accessed from web pages on different domains. Use a whitelist of allowed origins instead of allowing all origins in production for security.

Test your API with your frontend early to catch CORS issues. Use tools like browser DevTools to check network requests and CORS headers.

⚠️

Related Errors

Other common errors related to CORS include:

  • Preflight request failure: Happens when the browser sends an OPTIONS request before the actual request and the server does not respond correctly.
  • Missing headers: If allow_methods or allow_headers are not set properly, some requests may still fail.
  • Credentials issues: If you use cookies or authentication, set allow_credentials=True and ensure the frontend sends credentials.

Key Takeaways

Add CORSMiddleware to your FastAPI app to allow cross-origin requests.
Specify allowed origins to control which domains can access your API.
Use allow_methods and allow_headers to permit all needed HTTP methods and headers.
Set allow_credentials=True if your API uses cookies or authentication.
Test early with your frontend to catch CORS issues before deployment.