# Proxy with FastAPI

> Serve the MetricRaven script and events from a FastAPI app.

Source: https://metricraven.com/docs/proxy-fastapi  
Markdown: https://metricraven.com/docs/proxy-fastapi.md  
Section: Proxy

Two async FastAPI routes relay the script and events with httpx.

## Set it up

1. **Install httpx**

   ```bash
   pip install httpx
   ```

2. **Add the routes to your app**

   ```python title="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")
   ```

3. **Pass the visitor IP through Uvicorn**

   Behind a load balancer, start Uvicorn with `--proxy-headers` and set `--forwarded-allow-ips` to your proxy's address, so `request.client.host` is the visitor.

4. **Point your script tag at your own paths**

   Replace your MetricRaven tag with this one. `src` loads the tracker from your domain and `data-api` sends its events there too.

   ```html title="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](https://metricraven.com/docs/proxy).

## Details

- The proxy forwards only `Content-Type`, `Origin`, `User-Agent` and the visitor's IP as `x-visitor-ip`. Your site's cookies and auth headers never leave your server.
- `Origin` matters: MetricRaven checks it against your site's allowed domains. A missing or wrong origin is refused with `domain_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.
