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, Requestimport timeapp = 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_timeprint(f"Request: {request.url} | Time: {process_time}")return responseWhat 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:8000Without CORS → Browser blocks requestWith 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:8000Without CORS → Browser blocks request
With CORS → Request allowed
Enabling CORS in FastAPI
from fastapi.middleware.cors import CORSMiddlewareapp.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 production2. Blocking frontend due to missing CORS3. Writing heavy logic in middleware4. Not handling async properlyKey Takeaways
- Middleware runs before & after requests
- Useful for logging, auth, performance
- CORS allows frontend-backend communication
- Always restrict origins in production
Comments
Post a Comment