Assistenza/Guide proxy
Guide proxy

Proxy di Flowsery Analytics con FastAPI

Instrada Flowsery Analytics attraverso il tuo server FastAPI per evitare il blocco degli adblocker e raccogliere dati più precisi sui visitatori.

1. Installa le dipendenze

pip install fastapi uvicorn httpx

2. Configura il proxy

Aggiungi questo codice alla tua applicazione FastAPI:

from fastapi import FastAPI, Request
from fastapi.responses import Response
import httpx
 
app = FastAPI()
 
def get_client_ip(request: Request) -> str:
    """Resolve the actual visitor IP address"""
    # Prefer Cloudflare's CF-Connecting-IP if available
    if cf_connecting_ip := request.headers.get("cf-connecting-ip"):
        return cf_connecting_ip
 
    # Then X-Real-IP
    if x_real_ip := request.headers.get("x-real-ip"):
        return x_real_ip
 
    # Fall back to X-Forwarded-For (first entry)
    if x_forwarded_for := request.headers.get("x-forwarded-for"):
        return x_forwarded_for.split(",")[0].strip()
 
    # Last resort: direct connection host
    return request.client.host if request.client else ""
 
@app.get("/js/main.js")
async def proxy_script():
    async with httpx.AsyncClient() as client:
        response = await client.get('https://cdn.flowsery.com/main.js')
        return Response(
            content=response.content,
            media_type='application/javascript',
            headers={
                'Cache-Control': 'public, max-age=31536000'
            }
        )
 
@app.post("/api/track")
async def proxy_events(request: Request):
    body = await request.json()
 
    # Determine the origin from the request or construct it from the base URL
    origin = request.headers.get('origin') or str(request.base_url).rstrip('/')
 
    # Resolve visitor IP for accurate geolocation
    client_ip = get_client_ip(request)
 
    async with httpx.AsyncClient() as client:
        headers = {
            'Content-Type': 'application/json',
            'User-Agent': request.headers.get('user-agent'),
            'Origin': origin,
            'x-forwarded-for': client_ip
        }
 
        if client_ip:
            # CRITICAL: Flowsery reads this as the authoritative visitor IP. Without it, every visitor resolves to your server's region.
            headers['x-flowsery-real-ip'] = client_ip
 
        response = await client.post(
            'https://analytics.flowsery.com/analytics/events',
            json=body,
            headers=headers
        )
        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)

Nota: se la tua applicazione ha già un endpoint /api/track, usa l'attributo data-api sul tag script di Flowsery Analytics per indirizzare gli eventi a un percorso diverso. Per esempio, data-api="/flowsery-events" invia i dati a /flowsery-events.

Importante: se nella dashboard tutti i visitatori risultano nella stessa località, verifica che l'header x-flowsery-real-ip contenga l'IP reale del visitatore (non quello del server proxy) quando inoltri le richieste all'endpoint /events di Flowsery Analytics. Se FastAPI si trova dietro un altro proxy (Cloudflare, Vercel e così via), request.client.host sarà il proxy a monte: leggi invece direttamente cf-connecting-ip o x-real-ip.

3. Modifica il tag script

Sostituisci lo snippet originale di Flowsery Analytics con la versione che passa dal proxy:

<script defer data-fl-website-id="flid_******" src="/js/main.js"></script>

4. Pubblica

Dopo il deploy del server, la configurazione del proxy si attiva da sola.

Verifica che funzioni

Per controllare che il proxy funzioni correttamente:

  1. Vai sul tuo sito
  2. Apri gli strumenti per sviluppatori del browser e passa alla scheda Network
  3. Verifica che le richieste di analytics partano dal tuo dominio e non da analytics.flowsery.com