
Common Middleware: CORS, GZip, and Trusted Hosts
Master the standard middleware for production APIs. Learn how to configure CORS for frontend security and GZip for performance.
Common Middleware: CORS, GZip, and Trusted Hosts
While you can write custom middleware, FastAPI (and its base, Starlette) comes with a suite of "standard" middleware that solves 90% of common web infrastructure problems.
In this lesson, we learn to configure the three most critical ones: CORS, GZip, and Trusted Hosts.
1. CORS (Cross-Origin Resource Sharing)
By default, a web browser blocks a website (Origin A) from making an API request to another website (Origin B). This is a security feature to prevent malicious sites from reading your private data.
The CORS Challenge:
If your React app is at https://myapp.com and your FastAPI backend is at https://api.myapp.com, the browser will block the request unless you explicitly allow it using CORS Middleware.
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["https://myapp.com"], # Who can talk to you?
allow_credentials=True, # Can they send cookies/auth?
allow_methods=["*"], # Which verbs are allowed (?, POST, etc)
allow_headers=["*"], # Which headers are allowed?
)
2. GZip (Compression)
If your API returns large JSON objects (e.g., a list of 1,000 products), the data can be several megabytes in size. GZip Middleware compresses that data on the fly before sending it.
Why it’s helpful:
- Lower Latency: Compressed data travels faster over the internet.
- Reduced Data Costs: Essential for mobile users on limited data plans.
from fastapi.middleware.gzip import GZipMiddleware
app.add_middleware(GZipMiddleware, minimum_size=1000) # Only compress if > 1KB
3. Trusted Host Middleware
This is a security feature that ensures your app only responds to requests intended for a specific domain name. This prevents HTTP Host Header Attacks.
from fastapi.middleware.trustedhost import TrustedHostMiddleware
app.add_middleware(
TrustedHostMiddleware,
allowed_hosts=["shshell.com", "*.shshell.com"]
)
4. Where to Add Middleware?
You should add all your middleware in your main.py file, right after you initialize the FastAPI() app.
A Typical Production main.py:
app = FastAPI()
# 1. Security First
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["..."])
app.add_middleware(CORSMiddleware, ...)
# 2. Performance Next
app.add_middleware(GZipMiddleware)
# 3. Your App Routes...
Summary
- CORSMiddleware: Required for any API consumed by a web browser.
- GZipMiddleware: Vital for performance when dealing with large payloads.
- TrustedHostMiddleware: A simple layer of defense against networking attacks.
- Configuration: Add them in
main.pyto ensure they wrap your entire application.
In the next lesson, we’ll look at Custom Middleware Design, specifically focusing on performance and side effects.
Exercise: The Origin Check
If you set allow_origins=["*"] in your CORS configuration, what are the security implications? When is it acceptable to use the wildcard "*"?