# CrispStats: install reference for coding agents

Everything needed to add CrispStats to a web app in one pass. Source: https://crispstats.com/llms-install.txt. Human docs: https://docs.crispstats.com.

- This is the generic guide: replace `cs_pk_your_site_key` with the site's public key and `example.com` with its domain. The dashboard's "Set up with an AI agent" button links to a copy with the real values.
- `/k3x9qe` stands for the site's proxy path: any short path that starts with a letter. Avoid /stats and /analytics, which blockers list.

## Order of work

1. Detect the framework and the host. Say what you found.
2. Add the script element the framework's way (section 2). Only the element: never replace a layout, its metadata or its providers.
3. Add the proxy for the host (section 3), so ad blockers do not hide visits. Skip it on hosts without server code.
4. If the app takes payments, pass `crispstats.id()` into checkout metadata as `crispstats_visitor_id` (section 6).
5. If users sign in, add identify() where the session is known, and tell the owner what it means for privacy (section 7).
6. Verify with data-debug, then with the setup check, then remove data-debug (section 8).

There is no npm package to install. Do not add any package for CrispStats.

## 1. Script attributes

| Attribute | What it does |
| --- | --- |
| `data-site` | Required. The site's public key (`cs_pk_…`). Safe to publish. |
| `data-domains` | Comma-separated hostnames the script runs on, subdomains included. Preview deployments, workers.dev copies, staging and scrapers are not counted. Always set it to the site's domain. |
| `data-api` | Where events go: the collector origin, or the proxy path (`data-api="/k3x9qe"`). Events go to `<api>/e`, the visitor id comes from `<api>/id`. |
| `data-keep-params` | Query parameters to keep beyond the defaults. The script cuts every query string in the browser before sending; kept by default: utm_source, utm_medium, utm_campaign, utm_term, utm_content, ref, source, via, and ad click ids (gclid, gbraid, wbraid, msclkid, fbclid, ttclid, twclid, li_fat_id) with the value `1`. `"*"` keeps everything: do not use it, query strings carry license keys, reset tokens, session ids and e-mail addresses. |
| `data-hash` | Counts a `#/` or `#!/` route as part of the page, for hash routers (`/#/pricing`) only. Other fragments (#anchors, `#access_token=`) are never sent. A site with real paths does not need it. |
| `data-manual` | No automatic pageviews. Your code calls `crispstats.pageview()` on every page change. Custom events before the first pageview are dropped. Only for routers the script cannot see. |
| `data-exclude` | Paths not to track, comma-separated, `*` matches anything. Nothing is sent from an excluded page, custom events included. `/admin*` also matches /administrator and /admin-tools; write `/admin, /admin/*` for the section only. |
| `data-persist` | Persistent visitors: a random id in localStorage, sent as `vid`. Needs the site's Persistent visitors setting too (General settings), or the collector ignores it. It stores an identifier on the device: consent rules apply. The dashboard's snippet adds it when the setting is on. |
| `data-dnt` | Do not track browsers that send Do Not Track. Off by default. |
| `data-outbound` | Module: an `Outbound link` event on clicks to other sites. |
| `data-downloads` | Module: a `File download` event on links to files. Optionally a list of extensions. |
| `data-vitals` | Module: LCP, INP, CLS, FCP and TTFB from real visits. |
| `data-errors` | Module: uncaught errors and rejected promises. |
| `data-404` | Module: a `404` event on pages with `<meta name="crispstats:404">` (or an element matching a selector given as the value), or on a full page load whose navigation responseStatus is 404. At most one per pageview. |
| `data-debug` | Logs every event to the console and sends nothing. Runs on localhost and in automated browsers too. Each line starts `crispstats: <type> not sent (<reason>)`. For development and CI only. |
| `data-allow-localhost` | Sends real events from localhost. They count only if localhost is one of the site's hostnames. Never in production. |

Boolean attributes are bare in HTML (`data-outbound`) and an empty string in JSX and config objects (`data-outbound=""`): a bare JSX attribute renders as "true", which the script reads as a value.

Never put `id="crispstats"` on the script tag: browsers expose element ids as globals, so `window.crispstats` would be the element.

## 2. Install per framework

Each block is the proxied tag (`data-api="/k3x9qe"`). Without a proxy, drop `data-api` and load `https://in.crispstats.com/d.js` instead:

```html
<script
  defer
  data-site="cs_pk_your_site_key"
  data-domains="example.com"
  src="https://in.crispstats.com/d.js"
></script>
```

### HTML

Where: Inside <head>, on every page.

```html
<script
  defer
  data-site="cs_pk_your_site_key"
  data-domains="example.com"
  data-api="/k3x9qe"
  src="/k3x9qe/d.js"
></script>
```

### Next.js

Where: In app/layout.tsx, inside <body>. Pages Router: pages/_app.tsx, next to <Component />. File: `app/layout.tsx`.

This framework routes with real paths: never add `data-hash`.

```tsx
import Script from "next/script";

// Inside <body> in app/layout.tsx, after {children}.
<Script
  src="/k3x9qe/d.js"
  data-site="cs_pk_your_site_key"
  data-domains="example.com"
  data-api="/k3x9qe"
  strategy="afterInteractive"
/>
```

### React / Vite

Where: In index.html, inside <head>. Route changes are seen through the History API. File: `index.html`.

```html
<script
  defer
  data-site="cs_pk_your_site_key"
  data-domains="example.com"
  data-api="/k3x9qe"
  src="/k3x9qe/d.js"
></script>
```

### Vue / Nuxt

Where: In nuxt.config.ts. Plain Vue with Vite: the HTML tag in index.html. File: `nuxt.config.ts`.

This framework routes with real paths: never add `data-hash`.

```ts
export default defineNuxtConfig({
  app: {
    head: {
      script: [
        {
          src: "/k3x9qe/d.js",
          defer: true,
          "data-site": "cs_pk_your_site_key",
          "data-domains": "example.com",
          "data-api": "/k3x9qe",
        },
      ],
    },
  },
});
```

### Astro

Where: Inside <head> in your base layout. is:inline keeps Astro from bundling it. File: `src/layouts/Layout.astro`.

This framework routes with real paths: never add `data-hash`.

```html
<script
  defer
  is:inline
  data-site="cs_pk_your_site_key"
  data-domains="example.com"
  data-api="/k3x9qe"
  src="/k3x9qe/d.js"
></script>
```

### SvelteKit

Where: In src/app.html, inside <head>, above %sveltekit.head%. File: `src/app.html`.

This framework routes with real paths: never add `data-hash`.

```html
<script
  defer
  data-site="cs_pk_your_site_key"
  data-domains="example.com"
  data-api="/k3x9qe"
  src="/k3x9qe/d.js"
></script>
```

### Remix / React Router

Where: In app/root.tsx, inside <head>. File: `app/root.tsx`.

This framework routes with real paths: never add `data-hash`.

```tsx
{/* In the <head> of Layout (or App), next to <Meta /> and <Links />. */}
<script
  defer
  data-site="cs_pk_your_site_key"
  data-domains="example.com"
  data-api="/k3x9qe"
  src="/k3x9qe/d.js"
/>
```

### WordPress

Where: In your theme’s functions.php, or a small site plugin. File: `functions.php`.

This framework routes with real paths: never add `data-hash`.

```
// In your theme's functions.php, or a small site plugin.
add_action('wp_head', function () {
  ?>
  <script
    defer
    data-site="cs_pk_your_site_key"
    data-domains="example.com"
    data-api="/k3x9qe"
    src="/k3x9qe/d.js"
  ></script>
  <?php
});
```

### Webflow

Where: Site settings, Custom code, Head code. Then publish.

This framework routes with real paths: never add `data-hash`.

```html
<script
  defer
  data-site="cs_pk_your_site_key"
  data-domains="example.com"
  data-api="/k3x9qe"
  src="/k3x9qe/d.js"
></script>
```

### Framer

Where: Site settings, General, Custom code, End of <head> tag.

This framework routes with real paths: never add `data-hash`.

```html
<script
  defer
  data-site="cs_pk_your_site_key"
  data-domains="example.com"
  data-api="/k3x9qe"
  src="/k3x9qe/d.js"
></script>
```

### Shopify

Where: Online Store, Themes, Edit code: paste above </head> in theme.liquid. File: `layout/theme.liquid`.

This framework routes with real paths: never add `data-hash`.

```html
<script
  defer
  data-site="cs_pk_your_site_key"
  data-domains="example.com"
  data-api="/k3x9qe"
  src="/k3x9qe/d.js"
></script>
```

### Google Tag Manager

Where: A Custom HTML tag that fires on All Pages.

```html
<!-- Tag type: Custom HTML. Trigger: All Pages. -->
<script>
  (function () {
    var s = document.createElement("script");
    s.defer = true;
    s.setAttribute("data-site", "cs_pk_your_site_key");
    s.setAttribute("data-domains", "example.com");
    s.setAttribute("data-api", "/k3x9qe");
    s.src = "/k3x9qe/d.js";
    document.head.appendChild(s);
  })();
</script>
```

The Next.js element without a proxy:

```tsx
import Script from "next/script";

// Inside <body> in app/layout.tsx, after {children}.
<Script
  src="https://in.crispstats.com/d.js"
  data-site="cs_pk_your_site_key"
  data-domains="example.com"
  strategy="afterInteractive"
/>
```

## 3. Proxy through the site's own domain

One rule forwards `/k3x9qe/*` to `https://in.crispstats.com/p/*`.

- Forward only these request headers: `content-type`, `user-agent`, `accept-language`, `referer`, `origin`, `if-none-match`.
- Set `x-forwarded-for` to the visitor's address: `cf-connecting-ip`, else `x-real-ip`, else the first `x-forwarded-for` hop.
- Never forward `cookie` or `authorization`. A plain rewrite (next.config rewrites, Netlify _redirects, `new Headers(request.headers)`) forwards them: do not use one.
- Return only these response headers: `content-type`, `cache-control`, `etag`, `access-control-allow-origin`.
- Optional location hints: `x-crispstats-country` (ISO alpha-2), `x-crispstats-region`, `x-crispstats-city` (percent-encoded). Without them the country comes from the browser's timezone.
- Optional signature: `x-crispstats-proxy-secret` with the site's proxy secret (`cs_px_…`, shown in the dashboard under Tracking code, Advanced) from the env var `CRISPSTATS_PROXY_SECRET`. Never put it in browser code.
- If a Next.js proxy.ts (middleware) matches every path, leave `/k3x9qe` out of its matcher.

### Next.js

Where: A new file at app/k3x9qe/[...path]/route.ts (src/app/… if you use a src folder). If your proxy.ts matches every path, leave /k3x9qe out of its matcher. File: `app/k3x9qe/[...path]/route.ts`.

Visitor address and location: Works on Vercel, Node and any other host: the handler reads the visitor’s address and, on Vercel and Cloudflare, their location.

```ts
// Forwards /k3x9qe/* to in.crispstats.com. Sends only the headers below:
// never your visitors' cookies or authorization.
const UPSTREAM = "https://in.crispstats.com/p/";
const FORWARD = ["content-type", "user-agent", "accept-language", "referer", "origin", "if-none-match"];
const RETURN = ["content-type", "cache-control", "etag", "access-control-allow-origin"];

async function forward(request: Request, { params }: { params: Promise<{ path: string[] }> }) {
  const { path } = await params;
  // Plain segments only: nothing that could climb out of the collector's path.
  if (path.some((s) => s === "." || s === ".." || /[/\\]/.test(s))) return new Response(null, { status: 404 });
  const headers = new Headers();
  for (const name of FORWARD) {
    const value = request.headers.get(name);
    if (value) headers.set(name, value);
  }

  // The visitor's address: Cloudflare, then most hosts, then the first hop.
  const visitor =
    request.headers.get("cf-connecting-ip") ??
    request.headers.get("x-real-ip") ??
    request.headers.get("x-forwarded-for")?.split(",")[0]?.trim();
  if (visitor) headers.set("x-forwarded-for", visitor);

  // Where the visitor is, when the host says so (Vercel, Cloudflare).
  const country = request.headers.get("x-vercel-ip-country") ?? request.headers.get("cf-ipcountry");
  const region = request.headers.get("x-vercel-ip-country-region") ?? request.headers.get("cf-region-code");
  const city = request.headers.get("x-vercel-ip-city") ?? request.headers.get("cf-ipcity");
  if (country && /^[A-Z]{2}$/.test(country) && country !== "XX") headers.set("x-crispstats-country", country);
  if (region) headers.set("x-crispstats-region", region);
  // City names travel percent-encoded, as Vercel sends them. A malformed one is left out.
  if (city) {
    try {
      headers.set("x-crispstats-city", encodeURIComponent(decodeURIComponent(city)));
    } catch {
      // Send the hit without a city rather than fail it.
    }
  }

  const secret = process.env.CRISPSTATS_PROXY_SECRET;
  if (secret) headers.set("x-crispstats-proxy-secret", secret);

  const upstream = await fetch(UPSTREAM + path.join("/") + new URL(request.url).search, {
    method: request.method,
    headers,
    body: request.method === "POST" ? await request.arrayBuffer() : undefined,
    cache: "no-store",
  });
  const out = new Headers();
  for (const name of RETURN) {
    const value = upstream.headers.get(name);
    if (value) out.set(name, value);
  }
  return new Response(upstream.body, { status: upstream.status, headers: out });
}

export { forward as GET, forward as POST };
```

Signing (optional): Add the secret as CRISPSTATS_PROXY_SECRET in your host’s environment variables. The code above already sends it when it is set.

### Next.js on Cloudflare

Where: The same route handler, at app/k3x9qe/[...path]/route.ts. It runs as is under OpenNext and vinext. File: `app/k3x9qe/[...path]/route.ts`.

Visitor address and location: On Cloudflare the handler takes the address from cf-connecting-ip and the country from cf-ipcountry. Turn on the “Add visitor location headers” managed transform to pass the city too.

```ts
// Forwards /k3x9qe/* to in.crispstats.com. Sends only the headers below:
// never your visitors' cookies or authorization.
const UPSTREAM = "https://in.crispstats.com/p/";
const FORWARD = ["content-type", "user-agent", "accept-language", "referer", "origin", "if-none-match"];
const RETURN = ["content-type", "cache-control", "etag", "access-control-allow-origin"];

async function forward(request: Request, { params }: { params: Promise<{ path: string[] }> }) {
  const { path } = await params;
  // Plain segments only: nothing that could climb out of the collector's path.
  if (path.some((s) => s === "." || s === ".." || /[/\\]/.test(s))) return new Response(null, { status: 404 });
  const headers = new Headers();
  for (const name of FORWARD) {
    const value = request.headers.get(name);
    if (value) headers.set(name, value);
  }

  // The visitor's address: Cloudflare, then most hosts, then the first hop.
  const visitor =
    request.headers.get("cf-connecting-ip") ??
    request.headers.get("x-real-ip") ??
    request.headers.get("x-forwarded-for")?.split(",")[0]?.trim();
  if (visitor) headers.set("x-forwarded-for", visitor);

  // Where the visitor is, when the host says so (Vercel, Cloudflare).
  const country = request.headers.get("x-vercel-ip-country") ?? request.headers.get("cf-ipcountry");
  const region = request.headers.get("x-vercel-ip-country-region") ?? request.headers.get("cf-region-code");
  const city = request.headers.get("x-vercel-ip-city") ?? request.headers.get("cf-ipcity");
  if (country && /^[A-Z]{2}$/.test(country) && country !== "XX") headers.set("x-crispstats-country", country);
  if (region) headers.set("x-crispstats-region", region);
  // City names travel percent-encoded, as Vercel sends them. A malformed one is left out.
  if (city) {
    try {
      headers.set("x-crispstats-city", encodeURIComponent(decodeURIComponent(city)));
    } catch {
      // Send the hit without a city rather than fail it.
    }
  }

  const secret = process.env.CRISPSTATS_PROXY_SECRET;
  if (secret) headers.set("x-crispstats-proxy-secret", secret);

  const upstream = await fetch(UPSTREAM + path.join("/") + new URL(request.url).search, {
    method: request.method,
    headers,
    body: request.method === "POST" ? await request.arrayBuffer() : undefined,
    cache: "no-store",
  });
  const out = new Headers();
  for (const name of RETURN) {
    const value = upstream.headers.get(name);
    if (value) out.set(name, value);
  }
  return new Response(upstream.body, { status: upstream.status, headers: out });
}

export { forward as GET, forward as POST };
```

Signing (optional): Store the secret with wrangler, then redeploy. The handler reads it from process.env.CRISPSTATS_PROXY_SECRET.

```
npx wrangler secret put CRISPSTATS_PROXY_SECRET
```

### Vercel

Where: In vercel.json, for sites that are not Next.js. Vercel does not allow routes next to rewrites, redirects or headers in one file: if you use those, use a route handler instead. File: `vercel.json`.

Visitor address and location: Vercel adds the visitor’s address. The two transforms remove cookies and authorization before the request leaves.

```json
{
  "routes": [
    {
      "src": "/k3x9qe/(.*)",
      "dest": "https://in.crispstats.com/p/$1",
      "transforms": [
        { "type": "request.headers", "op": "delete", "target": { "key": "cookie" } },
        { "type": "request.headers", "op": "delete", "target": { "key": "authorization" } }
      ]
    }
  ]
}
```

Signing (optional): Add the secret as CRISPSTATS_PROXY_SECRET in the project’s environment variables, and this transform to the route.

```json
{ "type": "request.headers", "op": "set", "target": { "key": "x-crispstats-proxy-secret" }, "args": "$CRISPSTATS_PROXY_SECRET", "env": ["CRISPSTATS_PROXY_SECRET"] }
```

### Netlify

Where: A new edge function. A plain _redirects proxy would pass your visitors’ cookies along, so this one picks the headers. File: `netlify/edge-functions/crispstats.ts`.

Visitor address and location: Netlify gives the function the visitor’s address and location, and it passes both on.

```ts
// Forwards /k3x9qe/* to in.crispstats.com. Sends only the headers below:
// never your visitors' cookies or authorization.
import type { Config, Context } from "@netlify/edge-functions";

const PREFIX = "/k3x9qe/";
const UPSTREAM = "https://in.crispstats.com/p/";
const FORWARD = ["content-type", "user-agent", "accept-language", "referer", "origin", "if-none-match"];
const RETURN = ["content-type", "cache-control", "etag", "access-control-allow-origin"];

export default async (request: Request, context: Context) => {
  const url = new URL(request.url);
  const headers = new Headers();
  for (const name of FORWARD) {
    const value = request.headers.get(name);
    if (value) headers.set(name, value);
  }
  headers.set("x-forwarded-for", context.ip);
  if (context.geo.country?.code) headers.set("x-crispstats-country", context.geo.country.code);
  if (context.geo.subdivision?.code) headers.set("x-crispstats-region", context.geo.subdivision.code);
  if (context.geo.city) headers.set("x-crispstats-city", encodeURIComponent(context.geo.city));
  const secret = Netlify.env.get("CRISPSTATS_PROXY_SECRET");
  if (secret) headers.set("x-crispstats-proxy-secret", secret);

  const upstream = await fetch(UPSTREAM + url.pathname.slice(PREFIX.length) + url.search, {
    method: request.method,
    headers,
    body: request.method === "POST" ? await request.arrayBuffer() : undefined,
  });
  const out = new Headers();
  for (const name of RETURN) {
    const value = upstream.headers.get(name);
    if (value) out.set(name, value);
  }
  return new Response(upstream.body, { status: upstream.status, headers: out });
};

export const config: Config = { path: "/k3x9qe/*" };
```

Signing (optional): Add the secret as CRISPSTATS_PROXY_SECRET in the site’s environment variables. The code above already sends it when it is set.

### Cloudflare Worker

Where: A Worker on the route example.com/k3x9qe/*, in the zone that serves your site. File: `worker.js`.

Visitor address and location: The Worker passes the visitor’s address, country, region and city, and caches the script for a day.

```js
// A Worker on the route example.com/k3x9qe/*. Sends only the headers below:
// never your visitors' cookies or authorization.
const PREFIX = "/k3x9qe/";
const UPSTREAM = "https://in.crispstats.com/p/";
const FORWARD = ["content-type", "user-agent", "accept-language", "referer", "origin", "if-none-match"];
const RETURN = ["content-type", "cache-control", "etag", "access-control-allow-origin"];

export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    const headers = new Headers();
    for (const name of FORWARD) {
      const value = request.headers.get(name);
      if (value) headers.set(name, value);
    }
    headers.set("x-forwarded-for", request.headers.get("cf-connecting-ip") ?? "");
    const { country, regionCode, city } = request.cf ?? {};
    if (country && country !== "XX" && country !== "T1") headers.set("x-crispstats-country", country);
    if (regionCode) headers.set("x-crispstats-region", regionCode);
    if (city) headers.set("x-crispstats-city", encodeURIComponent(city));
    if (env.CRISPSTATS_PROXY_SECRET) headers.set("x-crispstats-proxy-secret", env.CRISPSTATS_PROXY_SECRET);

    const script = request.method === "GET" && url.pathname.endsWith(".js");
    const upstream = await fetch(UPSTREAM + url.pathname.slice(PREFIX.length) + url.search, {
      method: request.method,
      headers,
      body: request.method === "POST" ? request.body : undefined,
      // The script is the same for a day: keep it in this zone's cache.
      cf: script ? { cacheEverything: true, cacheTtl: 86400 } : undefined,
    });
    const out = new Headers();
    for (const name of RETURN) {
      const value = upstream.headers.get(name);
      if (value) out.set(name, value);
    }
    return new Response(upstream.body, { status: upstream.status, headers: out });
  },
};
```

Signing (optional): Store the secret on the Worker, then redeploy. The code above sends it when it is set.

```
npx wrangler secret put CRISPSTATS_PROXY_SECRET
```

### nginx

Where: Inside the server block of your site. Behind a load balancer, set real_ip_header first so $remote_addr is the visitor. File: `nginx.conf`.

Visitor address and location: nginx passes the visitor’s address. It does not know their location, so the country comes from the browser’s timezone.

```
location ^~ /k3x9qe/ {
  proxy_pass https://in.crispstats.com/p/;
  proxy_ssl_server_name on;
  proxy_set_header Host in.crispstats.com;

  # Only these headers go upstream: never your visitors' cookies or authorization.
  proxy_pass_request_headers off;
  proxy_set_header Content-Type $content_type;
  proxy_set_header User-Agent $http_user_agent;
  proxy_set_header Accept-Language $http_accept_language;
  proxy_set_header Referer $http_referer;
  proxy_set_header Origin $http_origin;
  proxy_set_header If-None-Match $http_if_none_match;
  proxy_set_header X-Forwarded-For $remote_addr;
}
```

Signing (optional): Add this line to the location block, with the secret in place of the placeholder.

```
proxy_set_header x-crispstats-proxy-secret "<your proxy secret>";
```

## 4. Collector routes

Under `https://in.crispstats.com/p` (what a proxy forwards to) the visitor is the first public X-Forwarded-For hop. On the direct routes it is the connecting address.

| Route | What it is |
| --- | --- |
| `GET /p/d.js`, `GET /p/<any name>.js` | The full script, through a proxy. `/p/d.core.js` is the core build. |
| `POST /p/e` | Events, through a proxy. |
| `GET /p/id?k=<key>`, `GET /api/id?k=<key>` | The visitor id, through a proxy. |
| `GET /p/check?k=<key>` | The setup check, through a proxy. |
| `GET /d.js`, `GET /js/script.js` | The full script, direct. Same file. |
| `GET /d.core.js` | The core build (no outbound, downloads, vitals, errors or 404 modules), direct. |
| `POST /e` | Events from the browser, direct. With `Authorization: Bearer cs_sk_…`, server-side events. |
| `POST /api/event` | Events forwarded by an older proxy rule. Same payload as /e. |
| `GET /id?k=<key>` | The visitor id, direct. Callable from the browser on any site. |
| `GET /check?k=<key>` | The setup check, direct. |

## 5. The JavaScript API

| Call | What it does |
| --- | --- |
| `crispstats(name, props?)` | A custom event. Declarative alternative: `data-cs-event="name"` on any element, props as `data-cs-prop-*`. |
| `crispstats.identify(userId, traits?)` | Ties the visitor to your user id for this page. See section 7. |
| `crispstats.revenue(amount, currency, props?)` | Revenue in minor units: `revenue(4900, "USD")`. Prefer connecting the payment provider (section 6). |
| `crispstats.pageview(url?)` | Counts a pageview now. Use after a route change the script missed, or on every change with `data-manual`. Never doubles an automatic view. |
| `crispstats.id()` | Promise of the visitor's anonymous id (32 hex), or undefined. Works through the proxy, and falls back to `https://in.crispstats.com/id` directly. |

Calls made before the script loads need the queue stub, above the script tag. It does not cover `id()`, which needs the loaded script (call it in a click handler).

```html
<!-- Above the script tag. Calls made before it loads wait here and run in order. -->
<script>
  if (typeof window.crispstats != "function") {
    var queue = [];
    var stub = function () { queue.push([].slice.call(arguments)); };
    stub.q = queue;
    ["identify", "revenue", "pageview"].forEach(function (method) {
      stub[method] = function () { queue.push(Object.assign([].slice.call(arguments), { m: method })); };
    });
    window.crispstats = stub;
  }
</script>
```

TypeScript: save this as `crispstats.d.ts` anywhere the project includes, then call `window.crispstats?.("signup")`.

```ts
// Types for window.crispstats, the global the tracking script installs.
interface CrispStatsGlobal {
  /** A custom event: crispstats("signup", { plan: "pro" }). */
  (name: string, props?: Record<string, unknown> | null): void;
  /** Ties this visitor to your own user id, for this page only. */
  identify(userId: string, traits?: Record<string, unknown> | null): void;
  /** Revenue in minor units (cents) with an ISO 4217 currency: revenue(4900, "USD"). */
  revenue(amount: number, currency: string, props?: Record<string, unknown> | null): void;
  /** Counts a pageview: the current URL, or the one given. */
  pageview(url?: string): void;
  /** The anonymous visitor id for this browser today, for payment metadata. */
  id(): Promise<string | undefined>;
  /** The script version; undefined on the queue stub. */
  v?: string;
}

interface Window {
  crispstats?: CrispStatsGlobal;
}
```

404 pages in Next.js (with `data-404` on the tag): in `app/not-found.tsx`, render the marker. React 19 hoists it into the head.

```tsx
export default function NotFound() {
  return (
    <>
      <meta name="crispstats:404" />
      {/* your not-found page */}
    </>
  );
}
```

## 6. Payments

Read the id in the browser, in the click handler that starts checkout, and pass it to the provider the way its section below says: for most, in the checkout's metadata as `crispstats_visitor_id`. Values that are not 32 lowercase hex characters are ignored. Without it the payment is still recorded, as Direct. The owner connects each provider with a key in the dashboard (Settings, Revenue): never handle that key or add a webhook yourself.

### Stripe

Put the id in the Checkout Session's metadata as crispstats_visitor_id; for subscriptions also in subscription_data.metadata, so renewals are attributed.

```js
// In the click handler that starts checkout (not while the page renders).
// undefined when the script is blocked or not tracking this browser: checkout still works.
const visitorId = await window.crispstats?.id?.();
// Send visitorId to the server route that creates the checkout.
```

```js
// Server, where you create the Checkout Session (stripe package)
const metadata = visitorId ? { crispstats_visitor_id: visitorId } : {};
const session = await stripe.checkout.sessions.create({
  // ...your line items, mode and URLs, unchanged
  metadata,
  subscription_data: { metadata }, // subscriptions only; leave out for one-time payments
});
```

- Leave client_reference_id alone: the metadata key is read first, so your own ids keep working. client_reference_id is only the alternative when you set nothing else, and only values of 32 hex characters are read from it.
- A Payment Link has no per-visitor metadata: append ?client_reference_id=<visitorId> to its URL instead.
- Payment Intents without Checkout: put crispstats_visitor_id in the Payment Intent's metadata.
- The id may sit on both the Checkout Session and the Payment Intent: the payment is still recorded once, because payments are stored under one id per provider (the payment intent for one-time Checkout, the invoice for subscriptions).

Connect it:

- Open https://crispstats.com/app (open the site, then Settings, Revenue, then Connect a payment provider, then Stripe): it opens the Stripe panel. A person does this, not an agent: the key must never pass through an agent or the code.
- The panel asks for: Stripe restricted key.
- Stripe restricted key: Create a restricted key in Stripe at https://dashboard.stripe.com/apikeys/create?name=CrispStats&permissions%5B%5D=rak_webhook_write&permissions%5B%5D=rak_checkout_session_read&permissions%5B%5D=rak_product_read&permissions%5B%5D=rak_invoice_read&permissions%5B%5D=rak_payment_intent_read&permissions%5B%5D=rak_charge_read. Stripe opens with the name and permissions filled in. Scroll down and choose Create key. Leave the permissions as they are. Copy the key and paste it into the panel. Keep the key. Deleting it stops new sales from reaching CrispStats.
- CrispStats creates its own webhook in Stripe, so new payments arrive within seconds, and checks every 15 minutes for anything it missed.
- CrispStats imports past payments and reads every payment from Stripe with the key before it counts as verified revenue. It never moves money.
- Do not add a webhook in Stripe by hand and do not send its payments to the payment API as well: either would count them twice.
- Check it: Connect a test or sandbox key and make a test payment: it shows with a Test tag and never counts as verified revenue. Connect the live key afterwards.

### Polar

Put the id in the checkout's metadata as crispstats_visitor_id.

```js
// In the click handler that starts checkout (not while the page renders).
// undefined when the script is blocked or not tracking this browser: checkout still works.
const visitorId = await window.crispstats?.id?.();
// Send visitorId to the server route that creates the checkout.
```

```js
// Server, where you create the checkout
const checkout = await polar.checkouts.create({
  // ...your products, unchanged
  metadata: visitorId ? { crispstats_visitor_id: visitorId } : {},
});
```

- The customer's external_id is read as your own user id.

Connect it:

- Open https://crispstats.com/app (open the site, then Settings, Revenue, then Connect a payment provider, then Polar): it opens the Polar panel. A person does this, not an agent: the token must never pass through an agent or the code.
- The panel asks for: Polar organization access token.
- Polar organization access token: Create an access token in Polar at https://polar.sh/dashboard. Open Settings, then Access tokens, and choose Create token. Name it CrispStats and choose No expiration. Tick orders:read, refunds:read, organizations:read and webhooks:write. Create the token and paste it into the panel. Sandbox or test account: https://sandbox.polar.sh/dashboard.
- With the webhooks:write scope on the token, CrispStats creates its own webhook and new payments arrive within seconds. Without it, they appear within 1 minute.
- CrispStats imports past payments and reads every payment from Polar with the token before it counts as verified revenue. It never moves money.
- Do not add a webhook in Polar by hand and do not send its payments to the payment API as well: either would count them twice.
- Check it: Connect a test or sandbox token and make a test payment: it shows with a Test tag and never counts as verified revenue. Connect the live token afterwards.

### Paddle

Put the id in the checkout's customData as crispstats_visitor_id.

```js
// In the click handler that starts checkout (not while the page renders).
// undefined when the script is blocked or not tracking this browser: checkout still works.
const visitorId = await window.crispstats?.id?.();
// Send visitorId to the server route that creates the checkout.
```

```js
Paddle.Checkout.open({
  // ...your items, unchanged
  customData: visitorId ? { crispstats_visitor_id: visitorId } : undefined,
});
```

Connect it:

- Open https://crispstats.com/app (open the site, then Settings, Revenue, then Connect a payment provider, then Paddle): it opens the Paddle panel. A person does this, not an agent: the key must never pass through an agent or the code.
- The panel asks for: Paddle API key.
- Paddle API key: Create an API key in Paddle at https://vendors.paddle.com/authentication-v2. Choose New API key and name it CrispStats. Leave Expires empty so the key never expires. Turn on Read for Transactions, Adjustments and Products. Turn on Write for Notification settings so sales show up the moment they happen. Copy the key and paste it into the panel. Sandbox or test account: https://sandbox-vendors.paddle.com/authentication-v2. Use a key from Paddle Billing, not Paddle Classic.
- After the key is checked, choose the products that count (picked for you when there is only one).
- With the Write permission for Notification settings on the key, CrispStats creates its own webhook and new payments arrive within seconds. Without it, they appear within 5 minutes.
- CrispStats imports past payments and reads every payment from Paddle with the key before it counts as verified revenue. It never moves money.
- Do not add a webhook in Paddle by hand and do not send its payments to the payment API as well: either would count them twice.
- Check it: Connect a test or sandbox key and make a test payment: it shows with a Test tag and never counts as verified revenue. Connect the live key afterwards.

### Dodo Payments

Put the id in the payment or subscription metadata as crispstats_visitor_id.

```js
// In the click handler that starts checkout (not while the page renders).
// undefined when the script is blocked or not tracking this browser: checkout still works.
const visitorId = await window.crispstats?.id?.();
// Send visitorId to the server route that creates the checkout.
```

```js
// Server, in the body of the payment or subscription you create
const body = {
  // ...your product cart and customer, unchanged
  metadata: visitorId ? { crispstats_visitor_id: visitorId } : {},
};
```

Connect it:

- Open https://crispstats.com/app (open the site, then Settings, Revenue, then Connect a payment provider, then Dodo Payments): it opens the Dodo Payments panel. A person does this, not an agent: the key must never pass through an agent or the code.
- The panel asks for: Dodo Payments API key.
- Dodo Payments API key: Open API keys in Dodo Payments at https://app.dodopayments.com/. Open Developer, then API keys, and choose Create new key. Name it CrispStats. Set Payments, Refunds, Subscriptions and Products to Read. Set Webhooks to Write so sales show up the moment they happen. Copy the key and paste it into the panel.
- With the Write permission for Webhooks on the key, CrispStats creates its own webhook and new payments arrive within seconds. Without it, they appear within 2 minutes.
- CrispStats imports past payments and reads every payment from Dodo Payments with the key before it counts as verified revenue. It never moves money.
- Do not add a webhook in Dodo Payments by hand and do not send its payments to the payment API as well: either would count them twice.
- Check it: Connect a test or sandbox key and make a test payment: it shows with a Test tag and never counts as verified revenue. Connect the live key afterwards.

### Creem

Put the id in the checkout's metadata as crispstats_visitor_id.

```js
// In the click handler that starts checkout (not while the page renders).
// undefined when the script is blocked or not tracking this browser: checkout still works.
const visitorId = await window.crispstats?.id?.();
// Send visitorId to the server route that creates the checkout.
```

```js
// Server, where you create the checkout
await fetch("https://api.creem.io/v1/checkouts", {
  method: "POST",
  headers: { "x-api-key": process.env.CREEM_API_KEY, "content-type": "application/json" },
  body: JSON.stringify({
    product_id: "prod_...",
    metadata: visitorId ? { crispstats_visitor_id: visitorId } : {},
  }),
});
```

- In test mode the API is https://test-api.creem.io.
- The customer's external_id is read as your own user id when the metadata has none.

Connect it:

- Open https://crispstats.com/app (open the site, then Settings, Revenue, then Connect a payment provider, then Creem): it opens the Creem panel. A person does this, not an agent: the key must never pass through an agent or the code.
- The panel asks for: Creem API key.
- Creem API key: Open API keys in Creem at https://creem.io/dashboard/developers. Turn off Test mode in the sidebar, then open Developers. Create a new API key named CrispStats. Give it Read on every scope, and Write on Webhooks so sales show up the moment they happen. Copy the key and paste it into the panel.
- With the Write permission for Webhooks on the key, CrispStats creates its own webhook and new payments arrive within seconds. Without it, they appear within 2 minutes.
- CrispStats imports past payments and reads every payment from Creem with the key before it counts as verified revenue. It never moves money.
- Do not add a webhook in Creem by hand and do not send its payments to the payment API as well: either would count them twice.
- Check it: Connect a test or sandbox key and make a test payment: it shows with a Test tag and never counts as verified revenue. Connect the live key afterwards.

### Whop

Create a checkout configuration on the server with the id in its metadata as crispstats_visitor_id, then send the visitor to its purchase URL. Payments made from it inherit the metadata.

```js
// In the click handler that starts checkout (not while the page renders).
// undefined when the script is blocked or not tracking this browser: checkout still works.
const visitorId = await window.crispstats?.id?.();
// Send visitorId to the server route that creates the checkout.
```

```js
// Server, with your own Whop API key (not the one given to CrispStats)
const response = await fetch("https://api.whop.com/api/v1/checkout_configurations", {
  method: "POST",
  headers: { authorization: `Bearer ${process.env.WHOP_API_KEY}`, "content-type": "application/json" },
  body: JSON.stringify({
    mode: "payment",
    plan_id: "plan_...",
    metadata: visitorId ? { crispstats_visitor_id: visitorId } : {},
  }),
});
const { purchase_url } = await response.json();
// Send the visitor to purchase_url
```

- Sales from Whop's own pages are counted without a visit.
- Whop's own tracking id (wuid) is never read as a visitor id.

Connect it:

- Open https://crispstats.com/app (open the site, then Settings, Revenue, then Connect a payment provider, then Whop): it opens the Whop panel. A person does this, not an agent: the key must never pass through an agent or the code.
- The panel asks for: Whop API key and Company ID.
- Whop API key: Open the Whop developer dashboard at https://whop.com/dashboard/developer. Under Account API keys, choose Create. Name it CrispStats and choose custom permissions. Tick Read payments, Read disputes and Manage webhooks. Copy the key and paste it into the panel. Sandbox or test account: https://sandbox.whop.com/dashboard/developer.
- Company ID: Open your Whop dashboard at https://whop.com/dashboard. Your company ID starts with biz_ and is in the address bar.
- With the Manage webhooks permission on the key, CrispStats creates its own webhook and new payments arrive within seconds. Without it, they appear within 1 minute.
- CrispStats imports past payments and reads every payment from Whop with the key before it counts as verified revenue. It never moves money.
- Do not add a webhook in Whop by hand and do not send its payments to the payment API as well: either would count them twice.
- Check it: Connect a test or sandbox key and make a test payment: it shows with a Test tag and never counts as verified revenue. Connect the live key afterwards.

### Razorpay

Put the id in the order's notes as crispstats_visitor_id; for a subscription, in the subscription's notes.

```js
// In the click handler that starts checkout (not while the page renders).
// undefined when the script is blocked or not tracking this browser: checkout still works.
const visitorId = await window.crispstats?.id?.();
// Send visitorId to the server route that creates the checkout.
```

```js
// Server, where you create the order
const order = await razorpay.orders.create({
  amount: 49900,
  currency: "INR",
  notes: visitorId ? { crispstats_visitor_id: visitorId } : {},
});

// Subscriptions: in the subscription's notes instead
const subscription = await razorpay.subscriptions.create({
  plan_id: "plan_...",
  total_count: 12,
  notes: visitorId ? { crispstats_visitor_id: visitorId } : {},
});
```

- Payments collected through Razorpay Invoices are not recorded: only checkout orders and subscription charges are.

Connect it:

- Open https://crispstats.com/app (open the site, then Settings, Revenue, then Connect a payment provider, then Razorpay): it opens the Razorpay panel. A person does this, not an agent: the key ID and secret must never pass through an agent or the code.
- The panel asks for: Razorpay key ID and Razorpay key secret.
- Razorpay key ID: Open API keys in Razorpay at https://dashboard.razorpay.com/app/website-app-settings/api-keys. Switch to Live mode, then open Account and Settings, then API keys. You need the Owner or Admin role. Copy the key ID, and the key secret you saved when you created it. If you no longer have the secret, generate a new one. Choose to keep the old key for 24 hours if Razorpay offers it, and update your checkout before then. Keep the key active so CrispStats can keep reading payments.
- Razorpay key secret: Razorpay keys cannot be limited: they can do anything your account can through the API, including refunds. CrispStats only reads payments and refunds.
- CrispStats reads new payments from Razorpay on a schedule: they appear within 2 minutes. There is no webhook to add.
- CrispStats imports past payments and reads every payment from Razorpay with the key ID and secret before it counts as verified revenue. It never moves money.
- Do not send Razorpay payments to the payment API as well: that would count them twice.
- Check it: Connect a test or sandbox key ID and secret and make a test payment: it shows with a Test tag and never counts as verified revenue. Connect the live key ID and secret afterwards.

### Freemius

Freemius REST payments do not expose custom checkout metadata fields, so call crispstats.identify() with the buyer's Freemius user id in FS.Checkout's purchaseCompleted callback on your site.

```js
// On your site, or when your signed-in customer already maps to a Freemius user id
window.crispstats?.identify(freemiusUserId);
```

```js
// In Freemius Checkout's purchaseCompleted callback
handler.open({
  plan_id: "1234",
  purchaseCompleted: function (response) {
    var uid = response?.purchase?.user_id || response?.user?.id;
    if (uid) window.crispstats?.identify(String(uid));
  },
});
```

- Freemius checkout payments carry the buyer's Freemius user ID when embedded via FS.Checkout: pass response.purchase.user_id to identify() in purchaseCompleted to link visits.
- If customers are already identified by your own auth user id, avoid overwriting identify() with a different id; hosted checkout.freemius.com redirects that bypass the site cannot carry a visitor id.

Connect it:

- Open https://crispstats.com/app (open the site, then Settings, Revenue, then Connect a payment provider, then Freemius): it opens the Freemius panel. A person does this, not an agent: the bearer token must never pass through an agent or the code.
- The panel asks for: API Bearer token and Product ID.
- API Bearer token: Copy your Freemius API Bearer token at https://dashboard.freemius.com/. Open your product in the Freemius Developer Dashboard and open Settings, API & Keys. Generate or copy the API Bearer Authorization Token and paste it into the panel. Enter the numeric Product ID shown on the same page.
- Product ID: Shown at the top of Settings, API & Keys in your product dashboard.
- CrispStats reads new payments from Freemius on a schedule: they appear within 2 minutes. There is no webhook to add.
- CrispStats imports past payments and reads every payment from Freemius with the bearer token before it counts as verified revenue. It never moves money.
- Do not send Freemius payments to the payment API as well: that would count them twice.
- Check it: Freemius marks test purchases itself: they show with a Test tag and never count as verified revenue.

### Lemon Squeezy

Put the id in the checkout's custom data as crispstats_visitor_id.

```js
// In the click handler that starts checkout (not while the page renders).
// undefined when the script is blocked or not tracking this browser: checkout still works.
const visitorId = await window.crispstats?.id?.();
// Send visitorId to the server route that creates the checkout.
```

```js
// A hosted checkout link
const url = new URL("https://your-store.lemonsqueezy.com/buy/your-variant");
if (visitorId) url.searchParams.set("checkout[custom][crispstats_visitor_id]", visitorId);
window.location.href = url.toString();

// Or, when you create the checkout through the API:
// checkout_data: { custom: { crispstats_visitor_id: visitorId } }
```

Connect it:

- Open https://crispstats.com/app (open the site, then Settings, Revenue, then Connect a payment provider, then Lemon Squeezy): it opens the Lemon Squeezy panel. A person does this, not an agent: the key must never pass through an agent or the code.
- The panel asks for: Lemon Squeezy API key.
- Lemon Squeezy API key: Create an API key in Lemon Squeezy at https://app.lemonsqueezy.com/settings/api. Choose the + next to API keys. Name it CrispStats and pick the latest expiry date offered. Copy the key and paste it into the panel.
- Lemon Squeezy API key: Lemon Squeezy keys cannot be limited. CrispStats only reads payments and creates one webhook.
- After the key is checked, choose the store (picked for you when there is only one).
- CrispStats creates its own webhook in Lemon Squeezy, so new payments arrive within seconds, and checks every 15 minutes for anything it missed.
- CrispStats imports past payments and reads every payment from Lemon Squeezy with the key before it counts as verified revenue. It never moves money.
- Lemon Squeezy closes on 31 March 2027. When you move to Stripe, connect Stripe here too.
- Do not add a webhook in Lemon Squeezy by hand and do not send its payments to the payment API as well: either would count them twice.
- Check it: Connect a test or sandbox key and make a test payment: it shows with a Test tag and never counts as verified revenue. Connect the live key afterwards.

### Shopify

The script does not run on Shopify's checkout, so save the id on the cart as the attribute __crispstats_vid: Shopify keeps it on the order and hides it from the buyer.

```liquid
{% comment %} layout/theme.liquid, below the CrispStats tag and above </head> {% endcomment %}
{% if cart.item_count > 0 %}
  <script>
    window.addEventListener("load", async function () {
      var privacy = window.Shopify && window.Shopify.customerPrivacy;
      if (privacy && privacy.analyticsProcessingAllowed && !privacy.analyticsProcessingAllowed()) return;
      var id = await window.crispstats?.id();
      if (!id) return;
      fetch(window.Shopify.routes.root + "cart/update.js", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ attributes: { __crispstats_vid: id } }),
      });
    });
  </script>
{% endif %}
```

- Check it: with an item in the cart, open /cart.js on the store; attributes should hold __crispstats_vid with 32 hexadecimal characters.
- Orders from visitors who declined analytics stay unlinked.
- An attribute named crispstats_visitor_id is read too, so a snippet added earlier keeps working.

Connect it:

- Open https://crispstats.com/app (open the site, then Settings, Revenue, then Connect a payment provider, then Shopify): it opens the Shopify panel. A person does this, not an agent: the client ID and secret must never pass through an agent or the code.
- The panel asks for: Store address, Client ID and Client secret.
- Store address: Settings, then Domains: the address ending in .myshopify.com.
- Client ID: Create an app in the Shopify Dev Dashboard at https://dev.shopify.com/dashboard/. Choose Create app and name it CrispStats. In a new version, add the scopes read_orders and read_all_orders. In the same version, under Protected customer data, select Orders, then release the version. Choose Install app and pick this store. Open Settings and copy the Client ID and Client secret into the panel.
- CrispStats creates its own webhook in Shopify, so new payments arrive within seconds, and checks every 15 minutes for anything it missed.
- CrispStats imports past payments and reads every payment from Shopify with the client ID and secret before it counts as verified revenue. It never moves money.
- Do not add a webhook in Shopify by hand and do not send its payments to the payment API as well: either would count them twice.
- Check it: Shopify marks test purchases itself: they show with a Test tag and never count as verified revenue.

### RevenueCat

Sign the customer in with the same id in the app (Purchases.logIn) and on the site (crispstats.identify). When the app knows the visitor id, set the subscriber attribute crispstats_visitor_id; on the web, pass it as purchase metadata.

```js
// In the click handler that starts checkout (not while the page renders).
// undefined when the script is blocked or not tracking this browser: checkout still works.
const visitorId = await window.crispstats?.id?.();
// Send visitorId to the server route that creates the checkout.
```

```js
// Web Billing: pass it with the purchase
await Purchases.getSharedInstance().purchase({
  rcPackage: pkg,
  metadata: visitorId ? { crispstats_visitor_id: visitorId } : {},
});

// Or keep it on the customer, so renewals carry it too
if (visitorId) Purchases.setAttributes({ crispstats_visitor_id: visitorId });
```

- To link a purchase to a visit, call Purchases.logIn in the app with the same id you pass to identify on your site.
- A Web Purchase Link takes the id as a URL parameter instead: ?metadata[crispstats_visitor_id]=<visitorId>.
- RevenueCat sends metadata with the first purchase only; subscriber attributes come with every event, so set the attribute when renewals should be attributed.
- Purchases through Web Billing and Stripe are counted through Stripe, and Paddle purchases through Paddle, if you connect them, so nothing counts twice. PayPal purchases made through RevenueCat are not counted.
- Connect only one of RevenueCat, Superwall and App Store to a site: they report the same Apple and Google sales, so a second one would count every sale twice.

Connect it:

- Open https://crispstats.com/app (open the site, then Settings, Revenue, then Connect a payment provider, then RevenueCat): it opens the RevenueCat panel. A person does this, not an agent: the key must never pass through an agent or the code.
- The panel asks for: RevenueCat secret API key.
- RevenueCat secret API key: Open API keys in RevenueCat at https://app.revenuecat.com/. Open your project's settings, then API keys, and choose New. Name it CrispStats and choose version 2. Under Customer information, set Customers, Subscriptions and Purchases to Read only. Under Project configuration, set Projects to Read only and Integrations to Read and write, so CrispStats can add its webhook. Leave everything else at No access, choose Generate, then copy the key and paste it into the panel.
- After the key is checked, choose the project (picked for you when there is only one).
- With write access to Integrations on the key, CrispStats creates its own webhook and new payments arrive within seconds. Without it, they appear within 1 day.
- CrispStats imports past payments and reads every payment from RevenueCat with the key before it counts as verified revenue. It never moves money.
- Do not add a webhook in RevenueCat by hand and do not send its payments to the payment API as well: either would count them twice.
- Check it: RevenueCat marks test purchases itself: they show with a Test tag and never count as verified revenue.

### Superwall

Sign the customer in with the same id in the app (Superwall.shared.identify) and on the site (crispstats.identify). When the app knows the visitor id, set the user attribute crispstats_visitor_id before the paywall opens.

```js
// On the site, when the customer signs in
window.crispstats?.identify(user.id);
```

```swift
// In the app (iOS), when the customer signs in
Superwall.shared.identify(userId: user.id)

// When the app knows the visitor id (a link from your site that opens the app)
Superwall.shared.setUserAttributes(["crispstats_visitor_id": visitorId])
```

- Purchases made through Stripe or a custom store are not counted here, so nothing counts twice. Connect Stripe, or the provider behind your custom store, to CrispStats to count them.
- Connect only one of RevenueCat, Superwall and App Store to a site: they report the same Apple and Google sales, so a second one would count every sale twice.

Connect it:

- Open https://crispstats.com/app (open the site, then Settings, Revenue, then Connect a payment provider, then Superwall): it opens the Superwall panel. A person does this, not an agent: the key must never pass through an agent or the code.
- The panel asks for: Superwall API key.
- Superwall API key: Open API keys in Superwall at https://superwall.com/dashboard. Open Settings, then API keys, and create a key named CrispStats. Under Read, tick Projects and Webhooks. Under Write, tick Webhooks. Under Project access, choose Restricted and pick this app's project. Copy the key and paste it into the panel.
- After the key is checked, choose the project (picked for you when there is only one).
- After the key is checked, choose the application (picked for you when there is only one).
- With write access to Webhooks on the key, CrispStats creates its own webhook and new payments arrive within seconds. Without it, they appear within 10 minutes.
- CrispStats imports past payments and reads every payment from Superwall with the key before it counts as verified revenue. It never moves money.
- Do not add a webhook in Superwall by hand and do not send its payments to the payment API as well: either would count them twice.
- Check it: Superwall marks test purchases itself: they show with a Test tag and never count as verified revenue.

### App Store

App Store report sales cannot be linked to a visit. There is no code to add: Apple's reports say what sold, not who bought it.

- App Store reports give the day of a sale, not the time.
- Apple keeps daily reports for one year.
- To link app purchases to visits, connect RevenueCat or Superwall instead.
- Connect only one of RevenueCat, Superwall and App Store to a site: they report the same Apple and Google sales, so a second one would count every sale twice.

Connect it:

- Open https://crispstats.com/app (open the site, then Settings, Revenue, then Connect a payment provider, then App Store): it opens the App Store panel. A person does this, not an agent: the key must never pass through an agent or the code.
- The panel asks for: Your .p8 key (a file), Issuer ID, Key ID and Vendor number.
- Your .p8 key: Open App Store Connect at https://appstoreconnect.apple.com/access/integrations/api. Choose Team Keys, then Generate API Key. You need the Admin or Account Holder role. Name it CrispStats and under Access choose Sales. Download the .p8 file and copy the Issuer ID and Key ID. Apple lets you download the file once.
- Vendor number: Open Payments and Financial Reports at https://appstoreconnect.apple.com/itc/payments_and_financial_reports. Find your vendor number next to your legal entity.
- Then choose Find my apps.
- After the key is checked, choose the apps that count (picked for you when there is only one).
- CrispStats reads new payments from App Store on a schedule: they appear within 32 hours. There is no webhook to add.
- CrispStats imports past payments and reads every payment from App Store with the key before it counts as verified revenue. It never moves money.
- Do not send App Store payments to the payment API as well: that would count them twice.
- Check it: App Store reports only real sales, so there is nothing to test with: the first real sale shows the connection works.

### Shopify App Store

Installs come from the Shopify App Store, so no visitor id travels with the charge. Call crispstats.identify() with the merchant's myshopify.com domain when they sign in on your site, and each earning is credited to that merchant's first visit.

```js
// When you know which shop the visitor manages, in lower case without https://
window.crispstats?.identify("their-store.myshopify.com");
```

- App installs come from the Shopify App Store, so no visit is linked unless your site calls identify with the store's myshopify.com domain.

Connect it:

- Open https://crispstats.com/app (open the site, then Settings, Revenue, then Connect a payment provider, then Shopify App Store): it opens the Shopify App Store panel. A person does this, not an agent: the token must never pass through an agent or the code.
- The panel asks for: Shopify Partner API token, Partner ID and App ID.
- Shopify Partner API token: Create a Partner API token at https://dev.shopify.com/dashboard/. Open Organization settings, then Users, then Security, and choose Add Partner API client. Name it CrispStats and tick View financials only. Choose Add client and copy the access token into the panel. Shopify shows it once.
- Partner ID: Open your app in the Partner Dashboard. Both IDs are in the address: partners.shopify.com/Partner ID/apps/App ID.
- CrispStats reads new payments from Shopify App Store on a schedule: they appear within 10 minutes. There is no webhook to add.
- CrispStats imports past payments and reads every payment from Shopify App Store with the token before it counts as verified revenue. It never moves money.
- Do not send Shopify App Store payments to the payment API as well: that would count them twice.
- Check it: Shopify App Store reports only real sales, so there is nothing to test with: the first real sale shows the connection works.

Other providers or your own billing: send payments to the payment API (docs: https://docs.crispstats.com/revenue/payment-api).

## 7. identify() and privacy

Call `window.crispstats?.identify(user.id)` only where a user is signed in, with your own user id. Do not pass e-mail addresses or names unless the owner asks for it.

Tell the owner: identify() ties visits to a known person, so that data is personal data under GDPR. The privacy policy has to say so, and depending on the jurisdiction consent may be needed. Without identify(), visitors are anonymous and counted per day.

Identify calls do not count as billable events; pageviews and custom events do.

Server-side events (a renewal, a webhook): `POST https://in.crispstats.com/e` with `Authorization: Bearer cs_sk_…` (a key with the Events scope, kept on the server):

```bash
curl -X POST https://in.crispstats.com/e \
  -H "Authorization: Bearer cs_sk_..." \
  -H "Content-Type: application/json" \
  -d '{"k":"cs_pk_your_site_key","t":"event","n":"subscription_renewed","u":"","p":{"plan":"pro"}}'
```

## 8. Verify

1. Add `data-debug` to the tag and load the app locally. The console shows one line per event, starting with `crispstats: pageview not sent (`. In CI, assert on that line: automated browsers are otherwise ignored.

```html
<script
  defer
  data-site="cs_pk_your_site_key"
  data-domains="example.com,localhost"
  data-debug
  src="https://in.crispstats.com/d.js"
></script>
```

2. Remove `data-debug`. Localhost is ignored without it, so a local page shows nothing in the dashboard. To send real events from localhost, use `data-allow-localhost` and add localhost to the site's hostnames:

```html
<script
  defer
  data-site="cs_pk_your_site_key"
  data-domains="example.com,localhost"
  data-allow-localhost
  src="https://in.crispstats.com/d.js"
></script>
```

3. After deploying, check `https://example.com/k3x9qe/d.js` returns JavaScript, then run the setup check.

Open `https://example.com/k3x9qe/check?k=cs_pk_your_site_key` (through the proxy) or `https://in.crispstats.com/check?k=cs_pk_your_site_key` (direct install). The answer is JSON and never contains an address:

| Field | Good value | Meaning |
| --- | --- | --- |
| `ok` | `true` | The key is known and, through a proxy, the address arrives, no cookies arrive and a required signature is present. |
| `site` | `"known"` | `"unknown"`: the key is wrong. |
| `proxied` | `true` through the proxy | `false` on the proxy path: the rule redirects instead of forwarding. |
| `visitorAddressForwarded` | `true` | `false`: set x-forwarded-for to the visitor's address, or every visitor merges into your server. |
| `cookiesForwarded` | `false` | `true`: the proxy leaks the visitor's cookies. Forward only the allowed headers. |
| `signed` | `true`, or `false` when not signing | `null` on a direct install. |
| `signatureRequired` | | The site only accepts signed proxied events. |
| `location.source` | `"proxy"` or `"edge"` | `"timezone"`: country only, from the browser. |
| `hostnames` | | The hostnames the site accepts. |

A request from a terminal carries no cookies, so `cookiesForwarded` is only meaningful when opened in a browser on the site itself.

4. The dashboard's Tracking code tab says "Receiving events" once a visit arrives. With the CrispStats MCP server connected, the `check_installation` tool reports the same.

## 9. Never

- Forward cookies or authorization headers through the proxy.
- Use `data-keep-params="*"`, or put tokens, e-mail addresses or license keys in kept parameters.
- Keep a direct `https://in.crispstats.com` script tag on checkout pages next to the proxied one: one tag per page.
- Put `id="crispstats"` on the script tag, or turn on `data-hash` for an app with real paths.
- Put a secret `cs_sk_` key or the proxy secret in browser code, or commit either.
- Replace a whole layout file to add the script.

## 10. MCP server

`https://crispstats.com/api/mcp` (Streamable HTTP, `Authorization: Bearer cs_sk_…` with the Read scope) has the tools `get_install_guide`, `check_installation` and `get_revenue_setup`, prompts for installing, connecting payments and explaining last week's numbers, and read-only analytics tools.
