> ## 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 analytics product. It has no self-hosted edition, no session replay, no heatmaps, no A/B testing and no data import except a site's history from a Plausible export (Settings, Import and export). Websites use the script. iOS, Android, React Native and Flutter use the mobile SDKs in the install guides. Those SDKs are source files, not a published package, and they do not read an advertising id.
> 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.
> The script tag is the main install; the npm package @crispstats/tracker does the same from code, never alongside the tag. 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.

# Install CrispStats from npm

> Add CrispStats to an app that bundles its JavaScript with the @crispstats/tracker package: init with your site key, track events and revenue, use the React component in Next.js, and send events from your server.

`@crispstats/tracker` is the same tracker as the script tag, as functions you import. It counts pageviews (single-page navigation included), sends custom events and revenue, and gives you the visitor id for checkout metadata. It sets no cookies, stores nothing on the device by default, has no dependencies and ships its own TypeScript types.

Use the package or the [script tag](https://docs.crispstats.com/install/overview.md) on a page, not both: each would count the visit.

You need your site's public key, which starts with `cs_pk_`. **Settings**, **Tracking code**, **npm** shows the code below with your key and domains filled in.

**1. Install the package**

```sh npm theme={"theme":{"light":"github-light","dark":"github-dark"}}
npm install @crispstats/tracker
```

```sh pnpm theme={"theme":{"light":"github-light","dark":"github-dark"}}
pnpm add @crispstats/tracker
```

```sh yarn theme={"theme":{"light":"github-light","dark":"github-dark"}}
yarn add @crispstats/tracker
```

**2. Start it with your site key**

Call `init` once, in code that runs in the browser, for example your app's entry file:

```ts src/main.ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { init } from "@crispstats/tracker";

init({
  site: "cs_pk_xxxxxxxx",
  domains: ["example.com"],
});
```

Importing the package touches no browser API, so it is safe in server rendering. Every function does nothing on the server and never throws.

**3. Deploy and check**

Visits on `localhost` are not counted. Deploy, then open your site in a normal browser window: your visit appears in **Realtime** within a few seconds. To see events locally, pass `debug: true`, which logs each event in the console and sends nothing.

## Track events and revenue

```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { track, identify, revenue, getVisitorId } from "@crispstats/tracker";

track("signup", { plan: "pro" });
identify("user_42", { plan: "team" });
revenue(4900, "USD"); // minor units: 49.00 USD
const visitorId = await getVisitorId();
```

| Function | What it does |
| - | - |
| `init(options)` | Starts tracking. The first call wins; later calls do nothing. |
| `track(name, props?)` | A [custom event](https://docs.crispstats.com/track/custom-events.md). Props are flat: strings, numbers, booleans or `null`. |
| `pageview(url?)` | Counts a pageview by hand. Only needed with `manual: true`, or for a router that does not use the History API. |
| `identify(userId, traits?)` | Ties this visit to your own user id, kept in memory for the page only. |
| `revenue(amount, currency, props?)` | Revenue in minor units with an ISO 4217 currency. |
| `getVisitorId()` | The anonymous visitor id, to put in your payment provider's metadata. See [visitor id at checkout](https://docs.crispstats.com/revenue/visitor-id-at-checkout.md). |

Calls made before `init` wait for it, up to 50 of them, so the order does not matter.

## Options

`init` takes the same options as the tag's [script attributes](https://docs.crispstats.com/tracking/script-attributes.md), as camel-case names:

| Option | Script attribute | What it does |
| - | - | - |
| `site` | `data-site` | Required. The site's public key. |
| `domains` | `data-domains` | Only track on these hostnames, subdomains included. |
| `api` | `data-api` | Where events go. A path on your own domain, such as `"/k3x9qe"`, sends them through your [proxy](https://docs.crispstats.com/tracking/proxy.md). |
| `exclude` | `data-exclude` | Paths not to track: `["/admin/*"]`. |
| `keepParams` | `data-keep-params` | Query parameters to keep on top of the campaign ones. |
| `hash` | `data-hash` | Counts `#/` routes as pages, for hash routers. |
| `manual` | `data-manual` | No automatic pageviews: call `pageview()` yourself. |
| `persist` | `data-persist` | Persistent visitors. Off by default; stores an id on the device, so it may need consent. |
| `respectDnt` | `data-dnt` | Skip browsers that send Do Not Track. |
| `allowLocalhost` | `data-allow-localhost` | Track on `localhost` too. |
| `debug` | `data-debug` | Log every event and send nothing. |
| `modules` | `data-outbound`, `data-downloads`, `data-vitals`, `data-errors`, `data-404` | Optional modules, below. |

### Modules

Each module is its own export, so your bundler drops the ones you do not pass:

```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { init, outbound, downloads, vitals, errors, notFound, checkouts } from "@crispstats/tracker";

init({
  site: "cs_pk_xxxxxxxx",
  modules: [outbound(), downloads(), vitals(), errors(), notFound(), checkouts()],
});
```

`outbound()` tracks clicks to other sites, `downloads({ extensions? })` file downloads, `vitals()` web vitals for the Performance page, `errors()` JavaScript errors for the Errors page, `notFound({ selector? })` 404 pages, and `checkouts()` adds the visitor id to hosted checkout links (Stripe Payment Links, Lemon Squeezy, Polar, Dodo Payments).

## React and Next.js

`<CrispStats />` takes the `init` options as props, starts tracking once after hydration and renders nothing. It is a client component, so a Next.js root layout can stay a server component:

```tsx app/layout.tsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { CrispStats } from "@crispstats/tracker/react";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <CrispStats site={process.env.NEXT_PUBLIC_CRISPSTATS_SITE!} domains={["example.com"]} />
      </body>
    </html>
  );
}
```

Navigation with `<Link>`, `router.push` and the back button is tracked with no extra code, in Next.js, React Router and TanStack Router alike. In client components, `useCrispStats()` returns `{ track, pageview, identify, revenue, getVisitorId }`:

```tsx components/upgrade-button.tsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
"use client";
import { useCrispStats } from "@crispstats/tracker/react";

export function UpgradeButton() {
  const { track } = useCrispStats();
  return <button onClick={() => track("upgrade clicked", { from: "settings" })}>Upgrade</button>;
}
```

React is an optional peer dependency: the root entry never imports it.

## From your server

`@crispstats/tracker/server` uses the global `fetch` only: Node 18 and later, Cloudflare Workers, Vercel Edge, Deno and Bun. Both helpers resolve to whether the collector accepted the request and never throw.

```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { trackServer } from "@crispstats/tracker/server";

await trackServer({
  site: "cs_pk_xxxxxxxx",
  apiKey: process.env.CRISPSTATS_API_KEY!, // a secret cs_sk_ key: never in browser code
  name: "subscription_renewed",
  props: { plan: "pro" },
  visitorId, // the getVisitorId() value you stored at checkout
});
```

`trackServer` also takes `userId`, `url` and `revenue: { amount, currency }`. Create the secret key under [API keys](https://docs.crispstats.com/account/api-keys.md).

`reportBotHit(request, { site })` reports AI crawler visits from middleware or an edge function, because crawlers never run JavaScript. It sends only the User-Agent, the path and the status. In Next.js, in `proxy.ts`:

```ts proxy.ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { NextResponse, type NextFetchEvent, type NextRequest } from "next/server";
import { reportBotHit } from "@crispstats/tracker/server";

export function proxy(request: NextRequest, event: NextFetchEvent) {
  event.waitUntil(reportBotHit(request, { site: process.env.NEXT_PUBLIC_CRISPSTATS_SITE! }));
  return NextResponse.next();
}
```

## Privacy

The package keeps the script's promises:

* No cookies and no fingerprinting. Nothing is written to the device unless you turn on `persist`, or the site owner opts their own browser out with the opt-out link in the site's settings.
* Each event carries the site key, the page URL with its query string cut to campaign parameters, the referrer, the screen width, the browser language, the timezone name and a timestamp.
* The IP address and User-Agent arrive with the request like with any request, and are not stored.

## Next steps

> [card] [Custom events](https://docs.crispstats.com/track/custom-events.md)
>
> Names, properties and the rules they follow.

> [card] [Visitor id at checkout](https://docs.crispstats.com/revenue/visitor-id-at-checkout.md)
>
> Link payments to the visit that brought them.

> [card] [Proxy](https://docs.crispstats.com/tracking/proxy.md)
>
> Send events through your own domain.


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