Performance: CORS middleware setup
This affects the initial network request handling and response time by adding headers to allow cross-origin requests.
Jump into concepts and practice - no test required
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"] )
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=["*"], )
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Allow all origins with '*' | 0 | 0 | 0 | [!] OK but can cause extra network delay |
| Restrict origins and methods | 0 | 0 | 0 | [OK] Best for performance and security |
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["https://example.com"],
allow_methods=["GET", "POST"],
allow_headers=["*"],
)
@app.get("/")
async def root():
return {"message": "Hello"}app.add_middleware(
CORSMiddleware,
allow_origins="*",
allow_methods=["GET", "POST"],
allow_headers=["*"]
)