0
0
FastAPIframework~8 mins

CORS middleware setup in FastAPI - Performance & Optimization

Choose your learning style9 modes available
Performance: CORS middleware setup
MEDIUM IMPACT
This affects the initial network request handling and response time by adding headers to allow cross-origin requests.
Allowing cross-origin requests safely and efficiently
FastAPI
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://example.com"],  # Restrict to trusted origins
    allow_credentials=True,
    allow_methods=["GET", "POST"],
    allow_headers=["Authorization", "Content-Type"]
)
Restricting origins and methods reduces unnecessary preflight requests and improves security.
📈 Performance GainReduces network round-trips and speeds up resource loading, improving LCP.
Allowing cross-origin requests safely and efficiently
FastAPI
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Allow all origins
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
Allowing all origins with '*' can cause security risks and unnecessary preflight requests, increasing latency.
📉 Performance CostTriggers extra OPTIONS preflight requests, adding network round-trips and delaying LCP.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Allow all origins with '*'000[!] OK but can cause extra network delay
Restrict origins and methods000[OK] Best for performance and security
Rendering Pipeline
CORS middleware runs on the server before the response is sent. It adds headers that control browser behavior for cross-origin requests, affecting network timing and resource loading.
Network Request Handling
Response Preparation
⚠️ BottleneckNetwork round-trips caused by preflight OPTIONS requests
Core Web Vital Affected
LCP
This affects the initial network request handling and response time by adding headers to allow cross-origin requests.
Optimization Tips
1Avoid using '*' for allow_origins to prevent extra preflight requests.
2Specify only needed HTTP methods and headers to reduce network overhead.
3Test CORS setup with browser DevTools to ensure minimal preflight requests.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a common performance issue caused by allowing all origins with '*' in CORS?
ALarger CSS file sizes
BExtra preflight OPTIONS requests causing network delays
CIncreased DOM reflows on the client
DSlower JavaScript execution
DevTools: Network
How to check: Open DevTools, go to Network tab, filter by 'OPTIONS' requests, and observe if preflight requests occur frequently.
What to look for: Fewer OPTIONS requests and faster response times indicate efficient CORS setup.