Proxy
Proxy with FastAPI
Two async FastAPI routes relay the script and events with httpx.
Set it up
Install httpx
terminalpip install httpxAdd the routes to your app
metricraven_proxy.py# metricraven_proxy.py · FastAPI with httpx import httpx from fastapi import FastAPI, Request, Response app = FastAPI() client = httpx.AsyncClient(timeout=15) async def relay(request: Request, url: str, cache_control: str) -> Response: headers = { name: request.headers[name] for name in ("content-type", "origin", "user-agent") if name in request.headers } if request.client: headers["x-visitor-ip"] = request.client.host try: upstream = await client.request( request.method, url, headers=headers, content=await request.body() if request.method == "POST" else None, ) except httpx.HTTPError: return Response(status_code=502) return Response( upstream.content, status_code=upstream.status_code, headers={ "Content-Type": upstream.headers.get("content-type", "application/octet-stream"), "Cache-Control": cache_control, }, ) @app.get("/a/script") async def metricraven_script(request: Request): return await relay(request, "https://metricraven.com/js/script.js", "public, max-age=3600") @app.post("/a/event") async def metricraven_event(request: Request): return await relay(request, "https://metricraven.com/api/v1/collect", "no-store")Pass the visitor IP through Uvicorn
Behind a load balancer, start Uvicorn with
--proxy-headersand set--forwarded-allow-ipsto your proxy's address, sorequest.client.hostis the visitor.Point your script tag at your own paths
Replace your MetricRaven tag with this one.
srcloads the tracker from your domain anddata-apisends its events there too.Your website's shared layout<script defer src="/a/script" data-api="/a/event" data-site-id="YOUR_SITE_ID"></script>
Verify it works
Open your live site. In the browser's Network panel, /a/script loads the tracker and /a/event answers with ok: true. Nothing goes to metricraven.com from the browser.
In Traffic, your own visit should show your real country and city. If every visit appears to come from your server's or host's location, the visitor IP isn't being forwarded.
Notes
- If a CDN or load balancer sits in front of this server, the connecting address is that proxy, not the visitor. Use the visitor IP header it sets (and only one it overwrites, so visitors can't fake it).
How the proxy works and which headers it must send: Use your own domain.
Details
- The proxy forwards only
Content-Type,Origin,User-Agentand the visitor's IP asx-visitor-ip. Your site's cookies and auth headers never leave your server. Originmatters: MetricRaven checks it against your site's allowed domains. A missing or wrong origin is refused withdomain_not_allowed.- MetricRaven allows about 120 events per minute per visitor IP. Without
x-visitor-ip, all of your visitors share the proxy's IP, so busy sites lose events as well as locations. - A proxy doesn't guarantee that every blocker will allow tracking.