Sign up

Proxy

Proxy with Flask

On this page

Two Flask routes relay the script and events with the requests library.

Set it up

  1. Install requests

    terminal
    pip install requests
  2. Add the routes to your app

    metricraven_proxy.py
    # metricraven_proxy.py · Flask 2.2+ with requests
    import requests
    from flask import Flask, Response, request
    
    app = Flask(__name__)
    # Behind a load balancer or CDN? Trust one proxy hop so remote_addr is the visitor:
    # from werkzeug.middleware.proxy_fix import ProxyFix
    # app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1)
    
    
    def relay(url, cache_control):
        headers = {
            name: request.headers[name]
            for name in ("Content-Type", "Origin", "User-Agent")
            if name in request.headers
        }
        headers["X-Visitor-IP"] = request.remote_addr or ""
        try:
            upstream = requests.request(
                request.method,
                url,
                headers=headers,
                data=request.get_data() if request.method == "POST" else None,
                timeout=15,
            )
        except requests.RequestException:
            return Response(status=502)
        return Response(
            upstream.content,
            status=upstream.status_code,
            headers={
                "Content-Type": upstream.headers.get("Content-Type", "application/octet-stream"),
                "Cache-Control": cache_control,
            },
        )
    
    
    @app.get("/a/script")
    def metricraven_script():
        return relay("https://metricraven.com/js/script.js", "public, max-age=3600")
    
    
    @app.post("/a/event")
    def metricraven_event():
        return relay("https://metricraven.com/api/v1/collect", "no-store")
  3. Trust your load balancer, if any

    Behind Nginx, Gunicorn on a platform router, or a CDN, request.remote_addr is that proxy. Enable the ProxyFix lines with the number of proxies in front of Flask.

  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.

    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.

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.