Source: https://datafa.st/docs/fastapi-proxy
Markdown source: https://datafa.st/docs/fastapi-proxy.md
Description: How to proxy DataFast analytics through your FastAPI server

# Proxy DataFast with FastAPI

Learn how to proxy DataFast analytics through your FastAPI server to bypass adblockers and improve accuracy.

## 1. Install Required Dependencies

```bash
pip install fastapi uvicorn httpx
```

## 2. Add Proxy Configuration

Add the following to your FastAPI application:

```python
from fastapi import FastAPI, Request
from fastapi.responses import Response
import httpx

app = FastAPI()

def get_client_ip(request: Request) -> str:
    """Get the real client IP address"""
    # Check X-Real-IP header first
    if x_real_ip := request.headers.get("x-real-ip"):
        return x_real_ip
    
    # Check X-Forwarded-For header
    if x_forwarded_for := request.headers.get("x-forwarded-for"):
        return x_forwarded_for.split(",")[0].strip()
    
    # Fallback to client.host
    return request.client.host if request.client else ""

@app.get("/js/script.js")
async def proxy_script():
    async with httpx.AsyncClient() as client:
        response = await client.get('https://datafa.st/js/script.js')
        return Response(
            content=response.content,
            media_type='application/javascript',
            headers={
                'Cache-Control': 'public, max-age=31536000'
            }
        )

@app.post("/api/events")
async def proxy_events(request: Request):
    body = await request.json()
    
    # Get origin from request or construct from base URL
    origin = request.headers.get('origin') or str(request.base_url).rstrip('/')
    
    # Get client IP for accurate location tracking
    client_ip = get_client_ip(request)
    
    async with httpx.AsyncClient() as client:
        response = await client.post(
            'https://datafa.st/api/events',
            json=body,
            headers={
                'Content-Type': 'application/json',
                'User-Agent': request.headers.get('user-agent'),
                'Origin': origin,
                'x-datafast-real-ip': client_ip
            }
        )
        return Response(
            content=response.content,
            media_type='application/json',
            status_code=response.status_code
        )

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
```

> **Note:** If you already have an `/api/events` API endpoint, add `data-api-url` to the DataFast script tag to send events to your own API endpoint. For example, `data-api-url="/datafast-events"` will send events to `/datafast-events` instead of `/api/events`. Read more [here](/docs/script-configuration#api-url-data-api-url-optional)

> **Important:** If you notice all visitors showing from the same location in your analytics, make sure you're sending the `x-datafast-real-ip` header with the actual visitor IP address (not your proxy server IP) when forwarding events to DataFast's `/api/events` endpoint.

## 3. Update Your Script Tag

Replace your existing DataFast script with the proxied version:

```html
<script
  defer
  data-website-id="dfid_******"
  data-domain="your_domain.com"
  src="/js/script.js"
></script>
```

## 4. Deploy your server

The proxy configuration will take effect automatically after deployment.

## Verification

To verify the proxy is working:
1. Visit your website
2. Open the network tab in your browser's developer tools
3. Check that analytics requests are going through your domain instead of datafa.st
