Proxy
Streaming HTTP responses, bidirectional WebSocket forwarding, and prefix proxy routes
Register proxy handlers with Starlette Route and WebSocketRoute, or build them with proxy_routes. FastHTML normal route injection parses request bodies before calling handlers; raw Starlette routes leave JSON, multipart, and binary bodies unread for streaming upstream.
Import proxy helpers explicitly from fasthtml.proxy rather than fasthtml.common.
from fasthtml.proxy import proxy_headers, proxy_routes
app = FastHTML()
app.router.routes += proxy_routes(
'/upstream', 'http://127.0.0.1:8000',
headers=lambda r: proxy_headers(r.headers, exclude=('authorization',), set={'x-user': r.session.get('auth')}),
ws=True,
)
Prefix routes
proxy_routes builds Starlette routes for a URL prefix, redirecting bare /prefix to /prefix/ with status 307 (preserving query strings), quoting forwarded paths, and optionally adding a matching WebSocketRoute. Register these routes after any application routes that take precedence, and perform access checks in before or custom handlers.
proxy_routes
def proxy_routes(
prefix, # URL prefix to mount, e.g. '/svelteit' or '/rusty'
target, # Upstream base URL string, or callable(conn) -> str
headers=None, # Forwarded headers, or callable(conn) -> headers; default uses proxy_headers
before=None, # Optional check callable(conn) (sync or async), or sequence of them; non-None return short-circuits
methods:tuple=('GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'), # HTTP methods accepted on the proxy routes
ws:bool=False, # Also register a WebSocketRoute at `{prefix}/{path:path}`?
redirect_root:bool=True, # Redirect bare `{prefix}` to `{prefix}/` (307, preserving query string)?
fallback=None, # Optional ASGI response for upstream connection failures
client=None, # Optional shared httpx2.AsyncClient; default uses a per-loop pooled client
):
Return Starlette Routes (and optional WebSocketRoute) proxying prefix to target.
Streaming HTTP responses
ProxyResponse streams request and response bodies without decoding them. It reuses a per-event-loop pooled httpx2.AsyncClient with cookie persistence disabled so upstream Set-Cookie headers do not leak across callers. Connection attempts time out after 10 seconds; transfers have no timeout.
ProxyResponse
def ProxyResponse(
request, # Incoming Starlette request
url, # Upstream URL without query parameters
headers=None, # Upstream request headers; default removes hop-by-hop fields
fallback=None, # Optional ASGI response for upstream connection failures
client=None, # Optional shared httpx2.AsyncClient; default uses a per-loop pooled client
):
Stream a request and response while keeping their transport open.
Header filtering
proxy_headers removes hop-by-hop headers, connection-nominated headers, and names in exclude or set, then appends non-None entries from set. Repeated end-to-end values stay separate with lowercase names.
proxy_headers
def proxy_headers(
headers, # Starlette or HTTPX headers exposing `.raw` pairs
exclude:tuple=(), # Additional header names (str or bytes, case-insensitive) to remove
set=None, # Mapping of header names to str or bytes values to set; always strips incoming headers with those names and skips None values
):
Remove hop-by-hop headers before forwarding, optionally stripping and setting headers.
WebSocket forwarding
proxy_websocket connects upstream before accepting the caller. Upstream HTTP 4xx and 5xx refusals forward their status, body, and content type via send_denial_response when supported, or accept and close with code 1008. It forwards the selected subprotocol, relays raw ASGI text and binary frames, and cancels the sibling task when either peer disconnects.
proxy_websocket
async def proxy_websocket(
websocket, # Incoming Starlette WebSocket, not yet accepted
url, # Complete upstream WebSocket URL, including query parameters
headers=None, # Additional upstream headers, as a mapping or string/byte pairs
):
Relay text and binary frames until either peer disconnects.