FastAPI CORS Middleware Fix
In this tutorial, you'll learn about FastAPI CORS Middleware Fix. We cover key concepts, practical examples, and best practices.
The Problem
A frontend app (React, Vue) at http://localhost:3000 tries to fetch from your FastAPI backend at http://localhost:8000. The browser blocks the request with a CORS error.
Quick Fix
Wrong — no CORS middleware
from fastapi import FastAPI
app = FastAPI()
@app.get("/api/items")
async def get_items():
return [{"id": 1, "name": "Item"}]
Output: Browser shows: Access to fetch at 'http://localhost:8000/api/items' from origin 'http://localhost:3000' has been blocked by CORS policy.
Correct — add CORSMiddleware
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000", "https://myapp.com"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
Output: Requests from allowed origins are permitted. Browser sends and receives data normally.
Development configuration
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allow all origins in development
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
Warning: Never use allow_origins=["*"] with allow_credentials=True in production.
Selective CORS by origin pattern
import re
app.add_middleware(
CORSMiddleware,
allow_origin_regex=r"https?://(localhost|myapp)\.(com|dev|app)",
allow_credentials=True,
allow_methods=["GET", "POST"],
allow_headers=["Authorization", "Content-Type"],
)
CORS with cookies (credentials)
# Backend
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Frontend JavaScript
fetch("http://localhost:8000/api/items", {
credentials: "include", # Send cookies
})
Exposing custom headers
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
expose_headers=["X-Total-Count", "X-Request-Id"],
)
Output: Browser allows JavaScript to read these response headers.
Prevention
- Add CORSMiddleware early in development to avoid wasted debugging time.
- Restrict
allow_originsto specific domains in production. - Never use
allow_origins=["*"]withallow_credentials=True.
Common Mistakes with cors middleware
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world FASTAPI code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro