๐Ÿ“ Fastapi

Middleware and CORS in FastAPI

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
332
๐ŸŒณ
Level
Advanced

Middleware processes requests and responses around FastAPI routes, while CORS controls which browser origins may access the API.

CORS (Cross-Origin Resource Sharing)

Allows browser clients to make requests to an API from a different domain.

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=["*"],      # GET, POST, PUT, DELETE, ...
    allow_headers=["*"],
)

For development (allow everything)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

Custom middleware

import time
from fastapi import Request

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

Request logging

import logging

logger = logging.getLogger(__name__)

@app.middleware("http")
async def log_requests(request: Request, call_next):
    logger.info(f"โ†’ {request.method} {request.url}")
    response = await call_next(request)
    logger.info(f"โ† {response.status_code}")
    return response

Authentication via middleware

from fastapi.responses import JSONResponse

@app.middleware("http")
async def auth_middleware(request: Request, call_next):
    if request.url.path.startswith("/api/private"):
        token = request.headers.get("Authorization")
        if not token or not verify_token(token):
            return JSONResponse({"detail": "Unauthorized"}, status_code=401)
    return await call_next(request)

BaseHTTPMiddleware (class-based)

from starlette.middleware.base import BaseHTTPMiddleware

class RateLimitMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        if is_rate_limited(request.client.host):
            return JSONResponse({"detail": "Too many requests"}, status_code=429)
        return await call_next(request)

app.add_middleware(RateLimitMiddleware)

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

HTTPException in FastAPI

Covered topics: Basic Usage, Status Codes, Error Details, Custom Headers.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 298
๐Ÿ“

Dependency Injection in FastAPI

Depends โ€” FastAPI's dependency injection system for reusing code across endpoints.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 306
๐Ÿ“

Testing FastAPI with pytest

Covered topics: Installation, TestClient (synchronous), Test database, Tests with fixtures.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 342

Did you like the article?

Subscribe to our updates and be the first to receive new articles. Grow with PyLand!