Skip to content

Cloudflare Workers

Serve the key and the endpoint from your domain with a Worker.

  1. Create a Worker with this code

    It forwards two routes and keeps the headers the ingest needs for country and browser.

    // worker.js
    const ORIGIN = "https://pisi.to";
    
    export default {
      async fetch(request) {
        const url = new URL(request.url);
    
        if (url.pathname === "/js/llave.js") {
          const res = await fetch(ORIGIN + "/js/llave.js", {
            cf: { cacheTtl: 86400, cacheEverything: true },
          });
          return new Response(res.body, res);
        }
    
        if (url.pathname === "/api/event") {
          const headers = new Headers(request.headers);
          // La ingesta necesita la IP real para el país. Nunca la guarda.
          headers.set("X-Forwarded-For", request.headers.get("CF-Connecting-IP"));
          return fetch(ORIGIN + "/api/event", {
            method: request.method,
            headers,
            body: request.body,
          });
        }
    
        return fetch(request);
      },
    };
    js
  2. Give it two routes

    example.com/js/llave.js and example.com/api/event, under the Worker's Triggers tab.

  3. Point the script at your domain

    data-api tells the key where to send events.

    <script defer
            data-domain="example.com"
            data-api="https://example.com/api/event"
            src="https://example.com/js/llave.js"></script>
    html

Check that it works

Open your site in a new tab and watch the dashboard: you should show up under "home right now" in under ten seconds. If you do not, run through the onboarding checklist.