Performance: Trusted host middleware
This affects the server response time and security by filtering requests based on allowed host headers before processing.
Jump into concepts and practice - no test required
from fastapi.middleware.trustedhost import TrustedHostMiddleware app = FastAPI() app.add_middleware(TrustedHostMiddleware, allowed_hosts=['example.com', 'www.example.com'])
app = FastAPI() from fastapi import Request, Response @app.middleware("http") async def check_host(request: Request, call_next): host = request.headers.get('host') if host not in ['example.com', 'www.example.com']: return Response('Invalid host', status_code=400) response = await call_next(request) return response
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Custom host check middleware | N/A (server-side) | N/A | N/A | [X] Bad |
| FastAPI TrustedHostMiddleware | N/A (server-side) | N/A | N/A | [OK] Good |
TrustedHostMiddleware in FastAPI?TrustedHostMiddleware is designed to filter incoming requests based on their host header.TrustedHostMiddleware to a FastAPI app?app.add_middleware() with the middleware class and keyword arguments.allowed_hosts, not hosts or allowed.from fastapi import FastAPI
from starlette.middleware.trustedhost import TrustedHostMiddleware
app = FastAPI()
app.add_middleware(TrustedHostMiddleware, allowed_hosts=['example.com', 'localhost'])
@app.get('/')
def read_root():
return {'message': 'Hello World'}from fastapi import FastAPI
from starlette.middleware.trustedhost import TrustedHostMiddleware
app = FastAPI()
app.add_middleware(TrustedHostMiddleware, allowed_hosts='example.com')
@app.get('/')
def home():
return {'msg': 'Welcome'}allowed_hosts parameter expects a list of strings, but a single string was given.example.com and also from localhost. Which allowed_hosts list correctly configures TrustedHostMiddleware for this?*.example.com to allow all subdomains.'*.example.com' which correctly matches all subdomains; others use incorrect patterns.