> ## Documentation Index
> Fetch the complete documentation index at: https://docs.crispstats.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> CrispStats is a hosted, privacy-first web analytics product. It has no self-hosted edition, no session replay, no heatmaps, no A/B testing, no mobile SDKs and no data import except a site's history from a Plausible export (Settings, Import and export).
> The script global is crispstats(...), site keys start with cs_pk_ and secret API keys start with cs_sk_. The script is served from https://in.crispstats.com/d.js and the REST API lives at https://crispstats.com/api/v1.
> There is no npm package to install. Integrations copy the script tag, the queue stub, crispstats.d.ts and proxy code from these docs or from Settings, Tracking code in the dashboard. A first-party proxy forwards one path of the site to https://in.crispstats.com/p/ and forwards only content-type, user-agent, accept-language, referer, origin, if-none-match and x-forwarded-for, never cookies.

# Pass the CrispStats visitor id to your checkout

> Get the anonymous visitor id with crispstats.id(), also behind a proxy and in a single-page app, and send it with your checkout as crispstats_visitor_id so CrispStats can attribute the payment.

A payment can only be attributed to a visit when the checkout carries that visitor's CrispStats id. Call `crispstats.id()` in the browser right before checkout, then put the id in the checkout's metadata (or custom data) as `crispstats_visitor_id`. The webhook brings the id back to CrispStats with the payment.

Without the id the payment is still recorded and counted in revenue, MRR and every total, but it is not tied to a visit: it is left out of the source, campaign and channel breakdowns rather than filed under **Direct**.

## Get the visitor id

```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
// Runs in the browser, on a page with the CrispStats script.
const visitorId = await crispstats.id();
```

It returns a Promise of a 32-character lowercase hex string: the id the collector files this browser's events under right now. Nothing is added to your reports.

Get the id in the visitor's browser, not on your server. The collector derives it from the browser's request, so a call from your server returns an id that belongs to your server.

### Behind a proxy

If you serve the script through your own domain (see [proxy the script](https://docs.crispstats.com/tracking/proxy.md)), `crispstats.id()` asks your proxy at `<your prefix>/id`, which forwards to `https://in.crispstats.com/p/id`. The collector reads the visitor's address from the `X-Forwarded-For` header your proxy sets, so the id is the same one your proxied pageviews are filed under. Nothing changes in your code.

If the proxy answers anything but the id (an old proxy rule that does not forward `/id`, an HTML error page), `crispstats.id()` asks `https://in.crispstats.com/id` directly instead. That direct id matches your events only when your proxy forwards the visitor's address, so check that once with the setup check described in [proxy the script](https://docs.crispstats.com/tracking/proxy.md).

You can also call the collector yourself from the browser. Both addresses keep working:

```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
const response = await fetch("https://in.crispstats.com/id?k=<public key>");
const { id } = await response.json();
```

### In a single-page app

In a single-page app (Next.js, React, Vue, SvelteKit), the script loads once and `crispstats.id()` works on every route, including routes that render the checkout button after a client-side navigation. You do not need the script tag on the checkout page itself. Call it in the click handler that starts the checkout, not while the page renders:

```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
"use client";

export function CheckoutButton({ priceId }: { priceId: string }) {
  async function startCheckout() {
    // undefined when the script is blocked or not tracking this browser: checkout still works
    const visitorId = await window.crispstats?.id?.();
    const response = await fetch("/api/checkout", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ priceId, visitorId }),
    });
    const { url } = await response.json();
    window.location.href = url;
  }
  return <button onClick={startCheckout}>Upgrade</button>;
}
```

The script must have loaded first: the queue stub described in [custom events](https://docs.crispstats.com/track/custom-events.md) cannot return a value, so it does not cover `crispstats.id()`. A click handler runs long after the script has loaded.

### When there is no id

`crispstats.id()` resolves to `undefined` instead of an id when the script is not tracking this browser, or when the request fails (for example, offline). The script does not track when:

* the page is on `localhost`, a `.localhost` name, `127.0.0.1`, `[::1]` or `file://` and `data-allow-localhost` is not set,
* the hostname is not in `data-domains`,
* the browser sends Do Not Track and the tag has `data-dnt`,
* the browser is automated, or the site owner excluded it with `localStorage.crispstats_ignore`.

`window.crispstats` exists in all of these cases, so the call is safe. It does not exist when the script did not load at all, for example because an ad blocker stopped it, so call it with optional chaining as above and send the visitor to checkout without the id. The payment is then recorded without a visit.

## Attach it to the checkout

CrispStats reads these fields from each payment it reads from the provider. Values that are not shaped like a visitor id (32 lowercase hex characters) are ignored.

| Provider | Where the id goes |
| - | - |
| Stripe Checkout | `crispstats_visitor_id` in the session's `metadata`. For subscriptions, also in `subscription_data.metadata`, so renewals are attributed. The alternative is `client_reference_id`, when you do not use it for your own ids. |
| Stripe Payment Links | `client_reference_id` in the link's URL. |
| Stripe Payment Intents without Checkout | `crispstats_visitor_id` in the Payment Intent's `metadata`. Payment Intents without it are not recorded. |
| Lemon Squeezy | `crispstats_visitor_id` in the checkout's custom data. |
| Polar | `crispstats_visitor_id` in the checkout's `metadata` (or in the customer's `metadata`). |
| Paddle | `crispstats_visitor_id` in the checkout's `customData`. |
| Dodo Payments | `crispstats_visitor_id` in the payment or subscription `metadata`. |
| Creem | `crispstats_visitor_id` in the checkout's `metadata`. |
| Razorpay | `crispstats_visitor_id` in the order's `notes`, or the subscription's `notes` for a subscription. |
| Whop | `crispstats_visitor_id` in the checkout configuration's `metadata`. See [Whop](https://docs.crispstats.com/revenue/whop.md#pass-the-visitor-id-at-checkout). |
| Shopify | The cart attribute `__crispstats_vid`, saved from your theme. See [Shopify](https://docs.crispstats.com/revenue/shopify.md#pass-the-visitor-id-at-checkout). |
| RevenueCat | Your user id as the app user id, matching `crispstats.identify()` on your site, or `crispstats_visitor_id` as a subscriber attribute. See [RevenueCat](https://docs.crispstats.com/revenue/revenuecat.md#link-purchases-to-visits). |
| Superwall | Your user id passed to `identify` in the app, matching `crispstats.identify()` on your site, or `crispstats_visitor_id` as a user attribute. See [Superwall](https://docs.crispstats.com/revenue/superwall.md#link-purchases-to-visits). |
| Shopify App Store | No visitor id travels with an install. Call `crispstats.identify()` with the merchant's myshopify.com domain. See [Shopify App Store](https://docs.crispstats.com/revenue/shopify-app-store.md#link-earnings-to-visits). |
| App Store | Not possible: Apple's sales reports do not say who bought. |

> [tab] Stripe
>
> Send the id from the browser to the server route that creates the Checkout Session (the button above), then put it in the metadata:
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> // Server (Node.js, stripe package), in the /api/checkout handler
> const { priceId, visitorId } = await request.json();
> const metadata = visitorId ? { crispstats_visitor_id: visitorId } : {};
> const session = await stripe.checkout.sessions.create({
>   mode: "subscription",
>   line_items: [{ price: priceId, quantity: 1 }],
>   success_url: "https://example.com/thanks",
>   metadata,
>   subscription_data: { metadata },
> });
> return Response.json({ url: session.url });
> ```
>
> For a one-time payment, leave out `subscription_data`. Your own `client_reference_id`, if you set one, stays as it is.
>
> For a Payment Link, which has no metadata you can set per visitor, add the id to the link's URL as `client_reference_id`:
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const visitorId = await window.crispstats?.id?.();
> const url = new URL("https://buy.stripe.com/your-link");
> if (visitorId) url.searchParams.set("client_reference_id", visitorId);
> window.location.href = url.toString();
> ```

> [tab] Lemon Squeezy
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const visitorId = await window.crispstats?.id?.();
> 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();
> ```
>
> When you create the checkout through the Lemon Squeezy API, put it in `checkout_data.custom`:
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> { "checkout_data": { "custom": { "crispstats_visitor_id": "<visitor id>" } } }
> ```

> [tab] Polar
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> // Server, when you create the checkout
> const checkout = await polar.checkouts.create({
>   // ...your products
>   metadata: { crispstats_visitor_id: visitorId },
> });
> ```
>
> CrispStats also reads the customer's `external_id` as your own user id.

> [tab] Paddle
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const visitorId = await window.crispstats?.id?.();
> Paddle.Checkout.open({
>   items: [{ priceId: "pri_123", quantity: 1 }],
>   customData: visitorId ? { crispstats_visitor_id: visitorId } : undefined,
> });
> ```

> [tab] Dodo Payments
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> // Server, in the body of the payment or subscription you create
> const body = {
>   // ...your product cart and customer
>   metadata: { crispstats_visitor_id: visitorId },
> };
> ```

> [tab] Creem
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> // Server, when 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: { crispstats_visitor_id: visitorId },
>   }),
> });
> ```
>
> In test mode the API is `https://test-api.creem.io`.

> [tab] Razorpay
>
> ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> // Server, when you create the order
> const order = await razorpay.orders.create({
>   amount: 49900,
>   currency: "INR",
>   notes: { crispstats_visitor_id: visitorId },
> });
>
> // Subscriptions: in the subscription's notes instead
> const subscription = await razorpay.subscriptions.create({
>   plan_id: "plan_...",
>   total_count: 12,
>   notes: { crispstats_visitor_id: visitorId },
> });
> ```

> [tab] RevenueCat
>
> ```swift theme={"theme":{"light":"github-light","dark":"github-dark"}}
> // In the app, when the customer signs in: the same id you pass to crispstats.identify() on your site
> let (customerInfo, created) = try await Purchases.shared.logIn(user.id)
>
> // Or, when the app knows the visitor id, keep it on the customer
> Purchases.shared.attribution.setAttributes(["crispstats_visitor_id": visitorId])
> ```
>
> Purchases through RevenueCat Web Billing are counted through the [Stripe connection](https://docs.crispstats.com/revenue/stripe.md), not RevenueCat, so nothing counts twice.

Each provider's page shows the same code, with what else that provider reads.

## Attribute across days with your user id

The visitor id rotates daily unless the site has [persistent visitors](https://docs.crispstats.com/privacy/persistent-visitors.md) on, so on its own it links a payment to visits from the same day. If your customers sign in, call [`crispstats.identify()`](https://docs.crispstats.com/track/identify-users) with your user id and also pass it at checkout as `crispstats_user_id` in the same metadata. CrispStats then takes the first touch from the earliest session of that user, whichever day it was.

```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
const session = await stripe.checkout.sessions.create({
  // ...
  metadata: { crispstats_visitor_id: visitorId, crispstats_user_id: user.id },
});
```

User ids are cut at 200 characters.

## Next steps

> [card] [Connect Stripe](https://docs.crispstats.com/revenue/stripe.md)
>
> Paste a restricted key; CrispStats creates the webhook.

> [card] [Payment API](https://docs.crispstats.com/revenue/payment-api.md)
>
> Report payments from any other provider or your own billing.

> [card] [How attribution works](https://docs.crispstats.com/revenue/overview.md)
>
> First-touch rules and the Revenue screen.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.