Topics in this subject
FastAPI 3 min read Updated 11 Aug 2026

Middleware and CORS

Adding CORS policies and custom request interceptors in FastAPI.

🧑‍🏫 Sabse pehle — simple mein samjho#

Jaise humne Node.js mein seekha tha, browsers security ke liye kisi aur website (origin) se API call allow nahi karte, jab tak backend usay explicitly allow na kare. Isko CORS kehte hain. FastAPI mein CORS configure karna ek inbuilt middleware ke zariye bohot asaan hai. Iske alawa, tum Node.js ki tarah apne custom middleware bhi bana sakte ho jo har request ko route pe aane se pehle aur jaane ke baad check karein (jaise execution time calculate karna).

1. Configuring CORS (Cross-Origin Resource Sharing)#

If your frontend (e.g., React on http://localhost:5173) tries to fetch data from your FastAPI backend (e.g., http://localhost:8000), the browser will block it with a CORS error.

You must add the CORSMiddleware to your FastAPI app.

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

app = FastAPI()

# 1. Define allowed origins (The URLs of your frontends)
origins = [
    "http://localhost:5173", # Vite local dev
    "https://my-production-app.com",
]

# 2. Add the middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True, # Allow cookies/auth headers to be sent
    allow_methods=["*"],    # Allow all HTTP methods (GET, POST, PUT, DELETE)
    allow_headers=["*"],    # Allow all headers
)

@app.get("/")
async def root():
    return {"message": "CORS enabled"}

2. Custom Middleware#

While Dependency Injection (Depends()) is the preferred way to share logic for specific routes, sometimes you need a piece of code to run for every single request that hits your server, regardless of the route. That is when you use Middleware.

In FastAPI, a middleware function is defined using the @app.middleware("http") decorator. It receives the request object and a call_next function.

Example: Calculating Execution Time#

import time
from fastapi import FastAPI, Request

app = FastAPI()

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    # --- Code executed BEFORE the route runs ---
    start_time = time.time()
    
    # Pass control to the route (or the next middleware)
    response = await call_next(request)
    
    # --- Code executed AFTER the route finishes ---
    process_time = time.time() - start_time
    
    # Modify the response (e.g., add a custom HTTP header)
    response.headers["X-Process-Time"] = str(process_time)
    
    return response

When to use Dependencies vs Middleware?#

  • Dependency (Depends): Use when you need access to the data inside the request (like validating a token, fetching a DB session, or reading body data) for specific routes.
  • Middleware: Use when you need to manipulate raw HTTP headers, handle CORS, log raw request paths globally, or modify the final response object for the entire application. Middlewares run before FastAPI even looks at your Pydantic models.