Skip to content

FastAPI CORS Middleware Fix

DodaTech Updated 2026-06-24 2 min read

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_origins to specific domains in production.
  • Never use allow_origins=["*"] with allow_credentials=True.

Common Mistakes with cors middleware

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead 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

### What is CORS?

Cross-Origin Resource Sharing. A browser security mechanism that blocks requests from a different origin (domain, protocol, port) unless the server explicitly allows it.

Why does CORS work in Postman but not the browser?

Postman and curl don't enforce CORS. Browsers enforce it to protect users from cross-origin attacks.

Can I use CORS without middleware?

Yes, by manually setting CORS headers in each response. But middleware is simpler and less error-prone.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro