Proxy DataFast with FastAPI

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

1. Install Required Dependencies

pip install fastapi uvicorn httpx

2. Add Proxy Configuration

Add the following to your FastAPI application:

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
            }
        )
        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

3. Update Your Script Tag

Replace your existing DataFast script with the proxied version:

<script
  defer
  data-website-id="dfid_******""
  data-domain="yourdomain.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
Something missing? Suggest features ✍️