Install DataPocket on JavaScript apps

Updated

React, Vue, Svelte or Angular: the script tag with typed calls, plus server-side payments and goals over HTTP. Sign in and these snippets fill in your site ID and domain. Until then, swap YOUR_SITE_ID and YOUR_DOMAIN with the values from your Install page.

  1. 1

    The datapocket npm package isn't on the npm registry yet, so `npm install datapocket` won't work. Add the script tag to index.html (or your framework's document head):

    html
    <script
      defer
      data-site-id="YOUR_SITE_ID"
      data-domain="YOUR_DOMAIN"
      src="https://datapocket.vo1d.studio/js/script.js"
    ></script>
  2. 2

    Call it from your code. This helper is typed and queues calls made before the script loads:

    ts
    // datapocket.ts
    type Props = Record<string, string | number | boolean>;
    declare global {
      interface Window { datapocket?: ((name: string, props?: Props) => void) & { q?: unknown[]; visitorId?: string } }
    }
    
    export function track(name: string, props?: Props) {
      const w = window;
      w.datapocket = w.datapocket || Object.assign((...args: unknown[]) => { (w.datapocket!.q = w.datapocket!.q || []).push(args); }, {});
      w.datapocket(name, props);
    }
    
    // later
    track("signup", { plan: "pro" });
  3. 3

    Server-side (Node, Bun, Deno, edge): record payments and goals with fetch. Every field is in the REST API reference (/reference/rest-api):

    ts
    const DP = "https://datapocket.vo1d.studio/api/v1";
    const headers = { Authorization: `Bearer ${process.env.DATAPOCKET_KEY}`, "Content-Type": "application/json" };
    
    await fetch(`${DP}/payments`, { method: "POST", headers,
      body: JSON.stringify({ amount: 49, currency: "USD", transaction_id: order.id, visitor_id: cookies.dp_vid }) });
    
    await fetch(`${DP}/goals`, { method: "POST", headers,
      body: JSON.stringify({ visitor_id: cookies.dp_vid, name: "trial_started" }) });

Related guides

Install DataPocket on JavaScript apps · DataPocket