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

# Proxy DataFast with Flask

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

## 1. Install Required Dependencies

```bash
pip install flask requests
```

## 2. Add Proxy Configuration

Add the following to your Flask application:

```python
from flask import Flask, request, Response
import requests

app = Flask(__name__)


def get_client_ip():
    """
    Return the real client IP address.
    If X-Forwarded-For exists (e.g. behind proxy/CDN), use the first value.
    Otherwise, fall back to Flask's request.remote_addr.
    """
    xff = request.headers.get("X-Forwarded-For")
    if xff:
        # Can be a comma-separated list: "client, proxy1, proxy2"
        parts = [ip.strip() for ip in xff.split(",")]
        if parts:
            return parts[0]  # left-most is always the original client IP
    return request.remote_addr


@app.route("/js/script.js")
def proxy_script():
    response = requests.get("https://datafa.st/js/script.js")
    return Response(
        response.content,
        content_type="application/javascript",
        headers={"Cache-Control": "public, max-age=31536000"},
    )


@app.route("/api/events", methods=["POST"])
def proxy_events():
    # Copy all incoming headers except those that must match the target
    excluded = {"host", "content-length"}
    headers = {
        key: value
        for key, value in request.headers.items()
        if key.lower() not in excluded
    }

    # Ensure Origin header is present (required by DataFast API)
    if "Origin" not in headers:
        scheme = request.scheme
        host = request.host
        headers["Origin"] = f"{scheme}://{host}"

    # Get real client IP for accurate location tracking
    client_ip = get_client_ip()
    headers["x-datafast-real-ip"] = client_ip

    # Forward the request body and headers to DataFast
    response = requests.post(
        "https://datafa.st/api/events",
        data=request.get_data(),
        headers=headers,
        timeout=5,
    )

    # Return DataFast's response back to the browser
    return Response(
        response.content,
        status=response.status_code,
        content_type=response.headers.get("Content-Type", "application/json"),
    )
```

> **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

## Troubleshooting

#### *All visitors showing from the same location*

If your analytics show all visitors from a single location (usually your server's location), your proxy isn't forwarding visitor IPs.

**To fix:**
1. Make sure your proxy sends 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
