Middleware & CORS in FastAPI

 

Introduction

As your API grows, you may need to:

  • Log requests
  • Modify responses
  • Handle cross-origin requests

This is where Middleware and CORS (Cross-Origin Resource Sharing) come into play.They help control how requests and responses flow through your application.

What is Middleware?

Middleware is a function that runs:

  • Before a request reaches your route
  • After a response is returned

Think of it as a pipeline layer between client and server.

Request Flow with Middleware

Client → Middleware → Route → Middleware → Response

Creating Custom Middleware

from fastapi import FastAPI, Request
import time

app = FastAPI()

@app.middleware("http")
async def log_requests(request: Request, call_next):
start_time = time.time()

response = await call_next(request)

process_time = time.time() - start_time
print(f"Request: {request.url} | Time: {process_time}")

return response

What This Middleware Does

  • Logs incoming request URL
  • Measures response time
  • Prints performance info

What is CORS?

CORS (Cross-Origin Resource Sharing) allows your API to be accessed from different domains.

Example:

  • Frontend → localhost:3000
  • Backend → localhost:8000

Without CORS → Browser blocks request
With CORS → Request allowed


What is CORS?

CORS (Cross-Origin Resource Sharing) allows your API to be accessed from different domains.

Example:

  • Frontend → localhost:3000
  • Backend → localhost:8000

Without CORS → Browser blocks request

With CORS → Request allowed


Enabling CORS in FastAPI

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # allow all (not recommended in prod)
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

Middleware Use Cases

  • Logging requests
  • Authentication checks
  • Performance monitoring
  • Adding custom headers

Common Mistakes

1. Allowing all origins in production
2. Blocking frontend due to missing CORS
3. Writing heavy logic in middleware
4. Not handling async properly

Key Takeaways

  • Middleware runs before & after requests
  • Useful for logging, auth, performance
  • CORS allows frontend-backend communication
  • Always restrict origins in production

Comments

Popular posts from this blog

Database Integration in FastAPI (SQLAlchemy CRUD)

Python Data Handling