title: Advanced Middleware
description: Add ASGI middleware, HTTPS redirect, trusted hosts, and GZip compression in JustAPI.
keywords: [JustAPI, middleware, ASGI, HTTPS redirect, trusted host, GZip]
Adding ASGI Middleware
JustAPI supports any ASGI middleware:
from justapi import JustAPIApp
from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware
from starlette.middleware.trustedhost import TrustedHostMiddleware
app = JustAPIApp()
app.add_middleware(HTTPSRedirectMiddleware)
Trusted Host Middleware
Guard against HTTP host header attacks:
app.add_middleware(
TrustedHostMiddleware,
allowed_hosts=["example.com", "*.example.com"],
)
GZip Compression
from starlette.middleware.gzip import GZipMiddleware
app.add_middleware(GZipMiddleware, minimum_size=500, compresslevel=9)
Custom ASGI Middleware
Write your own middleware class:
import time
from starlette.middleware.base import BaseHTTPMiddleware
class TimingMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
start = time.time()
response = await call_next(request)
duration = time.time() - start
response.headers["X-Process-Time"] = str(round(duration, 4))
return response
app.add_middleware(TimingMiddleware)
See Also
- Middleware — basic middleware usage
- Behind a Proxy — reverse proxy configuration
- Sub Applications — mounting sub-apps