> ## 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.

# Use CrispStats from TypeScript

> Type window.crispstats with a small declaration file, queue calls made before the script loads with a strict TypeScript stub, and call it safely from React, Vue or Svelte code.

CrispStats is a script tag, not an npm package: there is nothing to install. In a TypeScript app, two copy-paste files make the `window.crispstats` global typed and safe to call at any time:

* **`crispstats.d.ts`** declares the global, so `window.crispstats?.("signup")` type-checks.
* **The queue stub** installs a placeholder that queues calls made before the script has loaded. The script replays them in order.

Install the [script tag](https://docs.crispstats.com/install/overview.md) first. These files only add types and early calls.

## Add the global types

Save this as `crispstats.d.ts` anywhere your `tsconfig.json` includes, for example at the project root or in `src/`:

```ts crispstats.d.ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// 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;
}
```

The file has no `import` or `export`, so its declarations are global. The global is optional (`crispstats?`) because it is `undefined` until the stub or the script has run, and stays `undefined` when an ad blocker stops the script. Call it with `?.`:

```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
window.crispstats?.("signup", { plan: "pro" });
window.crispstats?.identify("user_42", { plan: "team" });
window.crispstats?.revenue(4900, "USD");
window.crispstats?.pageview();
```

## Queue calls made before the script loads

The script is deferred, so your app's code can run first. Run this stub as early as possible, before any code calls `crispstats`:

```ts crispstats-stub.ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// Queues crispstats() calls made before the script loads. The script replays them in order.
if (typeof window != "undefined") {
  const host = window as unknown as { crispstats?: unknown };
  if (typeof host.crispstats != "function") {
    const q: (unknown[] & { m?: string })[] = [];
    const queue = (m?: string) => (...args: unknown[]): void => {
      q.push(Object.assign(args, { m }));
    };
    host.crispstats = Object.assign(queue(), {
      q,
      identify: queue("identify"),
      revenue: queue("revenue"),
      pageview: queue("pageview"),
    });
  }
}
```

It is valid strict TypeScript: no `any`, no `arguments`, and it does nothing on the server. It installs itself only when `window.crispstats` is not already a function, so it never replaces the script if the script loaded first, and it replaces an element exposed by `id="crispstats"`. Each queued call is an array; a method call carries its name in `m`. The script replays the queue in order once it starts.

Where to run it:

| Framework | Place |
| - | - |
| Next.js | `instrumentation-client.ts` at the project root or in `src/`. Next.js runs it before the app is interactive. |
| React with Vite | `import "./crispstats-stub";` as the first line of `src/main.tsx`. |
| Nuxt | A client plugin, `plugins/crispstats.client.ts`, wrapped in `export default defineNuxtPlugin(() => { … })`. |
| SvelteKit | `src/hooks.client.ts`. |
| Plain HTML | Use the [HTML stub](https://docs.crispstats.com/tracking/script-attributes.md#call-the-global-before-the-script-loads) in a `<script>` above the tag instead. |

## Get the visitor id

`crispstats.id()` exists only on the loaded script, not on the stub, because it returns a value the stub cannot know. Call it from code that runs after the page has loaded, such as a click handler, and check that it is there:

```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
async function visitorId(): Promise<string | undefined> {
  const crispstats = window.crispstats;
  return typeof crispstats?.id == "function" ? crispstats.id() : undefined;
}
```

It resolves to `undefined` when the script is not tracking, in [debug mode](https://docs.crispstats.com/tracking/localhost-and-testing.md#debug-mode), or when the request fails. See [visitor id at checkout](https://docs.crispstats.com/revenue/visitor-id-at-checkout.md).

## Use it from components

The global works the same in every framework. In React:

```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
export function UpgradeButton() {
  return <button onClick={() => window.crispstats?.("upgrade clicked", { from: "settings" })}>Upgrade</button>;
}
```

Props are flat: strings, numbers, booleans and `null`. Anything else is sent as its string form. See [custom events](https://docs.crispstats.com/track/custom-events.md#event-and-property-rules).

## Next steps

> [card] [Next.js](https://docs.crispstats.com/install/nextjs.md)
>
> The script element, a proxy route handler and 404s.

> [card] [Custom events](https://docs.crispstats.com/track/custom-events.md)
>
> Track signups, clicks and other actions with properties.

> [card] [Script attributes](https://docs.crispstats.com/tracking/script-attributes.md)
>
> Every option and method of the global.


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