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

# Add CrispStats to a Next.js app

> Add the CrispStats script to a Next.js app with one next/script element, type the global, proxy it through a route handler, mark 404 pages and report AI crawlers from proxy.ts.

To add CrispStats to a Next.js app, put one `next/script` element in `app/layout.tsx`. Navigation between routes (`<Link>`, `router.push`, the back button) is tracked for you, so you need no `usePathname` effect. Everything else on this page is optional: types for the global, a first-party proxy, 404 tracking and AI crawler reports. There is no npm package to install.

You need your site's public key, which starts with `cs_pk_`. **Settings**, **Tracking code**, **Next.js** shows every snippet on this page with your key and domain filled in.

## Add the script

**1. Add the Script element to the root layout**

Open `app/layout.tsx` (or `src/app/layout.tsx`). Import `Script` at the top and add the element inside `<body>`, after `{children}`. Change nothing else in the file: your metadata, fonts and providers stay as they are.

```tsx app/layout.tsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
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_xxxxxxxx"
  data-domains="example.com"
  strategy="afterInteractive"
/>
```

Replace the key and the domain with yours. `data-domains` keeps preview deployments and copies of your site on other hosts from being counted. List more hostnames with commas: `data-domains="example.com,example.org"`.

**Pages Router**: add the same import and element to `pages/_app.tsx`, next to `<Component {...pageProps} />`.

**2. Deploy and check**

Deploy, then open your production site in a normal browser window. Visits to `next dev` on `localhost:3000` are not counted: see [test locally](#test-locally). Your visit shows in **Realtime** within a few seconds, and **Settings**, **Tracking code** shows **Receiving events.**

### Why this element and these props

* **`strategy="afterInteractive"`** loads the script right after the page becomes interactive, so it never delays your page. Do not use `lazyOnload`, which loads it so late that short visits are missed, or `beforeInteractive`, which it does not need. Because the script starts after your app, it watches route changes through both the History API and the Navigation API; if route changes still go missing in some browsers, see [routers that saved pushState early](https://docs.crispstats.com/tracking/single-page-apps.md#routers-that-saved-pushstate-early).
* **No `id` prop.** `next/script` needs an `id` only for inline scripts. Do not add `id="crispstats"`: browsers expose an element's id as a global, so `window.crispstats` would be the `<script>` element until the script loads, and early calls throw.
* **Flags take an empty string.** In JSX, write `data-outbound=""`, not a bare `data-outbound`, which renders as `data-outbound="true"`. See [write flag attributes](https://docs.crispstats.com/tracking/script-attributes.md#write-flag-attributes).
* **No `data-hash`.** Next.js routes with real paths, and `data-hash` only reads routes written after `#`, such as `/#/pricing`.

Add options from **Settings**, **Tracking code** (outbound links, downloads, web vitals, errors, 404 pages) as props on the same element. [Script attributes](https://docs.crispstats.com/tracking/script-attributes.md) lists them all.

### As a component

If you prefer a component, this file renders only the element. Render `<CrispStats />` inside `<body>` in `app/layout.tsx`:

```tsx app/crispstats.tsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
import Script from "next/script";

export function CrispStats() {
  return (
    <Script
      src="https://in.crispstats.com/d.js"
      data-site="cs_pk_xxxxxxxx"
      data-domains="example.com"
      strategy="afterInteractive"
    />
  );
}
```

It is a server component: `next/script` handles the client side.

## Send events with types

The script installs `window.crispstats`. Two small files make it typed and safe to call before the script loads. Both come from [TypeScript](https://docs.crispstats.com/install/typescript.md), where they are explained.

**1. Add the global types**

Save this as `crispstats.d.ts` at the project root, next to `next-env.d.ts`. Next.js projects include every `.d.ts` file there.

```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;
}
```

**2. Queue calls made before the script loads**

Put this in `instrumentation-client.ts` at the project root (or in `src/`). Next.js runs that file before your app becomes interactive, so the queue exists before any component calls `crispstats`. If the file already exists, add the code to it.

```ts instrumentation-client.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"),
    });
  }
}
```

**3. Call it from a client component**

```tsx app/pricing/upgrade-button.tsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
"use client";

export function UpgradeButton() {
  return (
    <button onClick={() => window.crispstats?.("upgrade clicked", { from: "pricing" })}>
      Upgrade
    </button>
  );
}
```

The optional call (`?.`) keeps the button working when an ad blocker stops the script and the stub is missing. For clicks you can also use `data-cs-event` attributes and no JavaScript: see [declarative events](https://docs.crispstats.com/track/declarative-events.md).

## Proxy through your domain

To count visitors whose ad blocker stops `in.crispstats.com`, serve the script and events from a path on your own site. In Next.js that is one route handler and a changed `Script` element. Nothing goes in `next.config.ts` or `next.config.mjs`: a rewrite there would forward your visitors' cookies.

**1. Add the route handler**

**Settings**, **Tracking code**, **Proxy through your own domain** proposes a path for your site, such as `/k3x9qe`. Create `app/k3x9qe/[...path]/route.ts` with your path as the folder name:

```ts app/k3x9qe/[...path]/route.ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// 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 };
```

It forwards only the headers listed in the comment, sets `x-forwarded-for` to the visitor's address, passes the visitor's location on Vercel and Cloudflare, and returns only `content-type`, `cache-control`, `etag` and `access-control-allow-origin`. It never forwards `cookie` or `authorization`.

**2. Point the Script element at the path**

```tsx app/layout.tsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
import Script from "next/script";

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

**3. Check it**

After you deploy, open `https://example.com/k3x9qe/check?k=cs_pk_xxxxxxxx` on your site. Look for `"proxied": true`, `"visitorAddressForwarded": true` and `"cookiesForwarded": false`. See [check it works](https://docs.crispstats.com/tracking/proxy.md#check-it-works).

If your `proxy.ts` (or `middleware.ts`) runs on every path, leave the proxy path out of its matcher, as the [AI crawler example](#report-ai-crawlers-from-proxy-ts) below does.

### Next.js on Cloudflare: OpenNext and vinext

The same route handler runs as is under OpenNext (`@opennextjs/cloudflare`) and vinext. On Cloudflare it reads the visitor's address from `cf-connecting-ip` and the country from `cf-ipcountry`; turn on the **Add visitor location headers** managed transform in Cloudflare to pass the region and city too. To [sign the requests](https://docs.crispstats.com/tracking/proxy.md#sign-proxied-requests), store the secret with `npx wrangler secret put CRISPSTATS_PROXY_SECRET` and redeploy.

vinext keeps its own reference to `history.pushState`, so the script sees its route changes through the Navigation API, in browsers that have it. If route changes are missing in other browsers, use [manual pageviews](https://docs.crispstats.com/tracking/single-page-apps.md#manual-pageviews).

## Track 404 pages

Add `data-404=""` to the `Script` element, then mark the not-found page. In the App Router, add the marker to `app/not-found.tsx`:

```tsx app/not-found.tsx (element) theme={"theme":{"light":"github-light","dark":"github-dark"}}
export default function NotFound() {
  return (
    <main>
      {/* Tells CrispStats this page is a 404. React moves it into <head>. */}
      <meta name="crispstats:404" content="1" />
      <h1>Page not found</h1>
    </main>
  );
}
```

```tsx app/not-found.tsx (metadata) theme={"theme":{"light":"github-light","dark":"github-dark"}}
import type { Metadata } from "next";

export const metadata: Metadata = {
  // Rendered as <meta name="crispstats:404" content="1">.
  other: { "crispstats:404": "1" },
};

export default function NotFound() {
  return (
    <main>
      <h1>Page not found</h1>
    </main>
  );
}
```

```tsx pages/404.tsx (Pages Router) theme={"theme":{"light":"github-light","dark":"github-dark"}}
import Head from "next/head";

export default function NotFound() {
  return (
    <>
      <Head>
        <meta name="crispstats:404" content="1" />
      </Head>
      <h1>Page not found</h1>
    </>
  );
}
```

The element version works in any component, server or client: React 19 hoists `<meta>` into `<head>`, and the script finds it anywhere in the document either way. Use the metadata version only in `app/not-found.tsx` or `app/global-not-found.tsx`, which support a `metadata` export. A `notFound()` call in a page renders the nearest `not-found.tsx`, so it is marked too. See [404 pages](https://docs.crispstats.com/track/404-pages.md) for when the check runs.

## Test locally

The script ignores `localhost` and automated browsers, so `next dev` and Playwright runs show nothing in the dashboard. Turn on debug mode in development to see every event in the console instead, without sending anything:

```tsx app/layout.tsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
<Script
  src="https://in.crispstats.com/d.js"
  data-site="cs_pk_xxxxxxxx"
  data-domains="example.com,localhost"
  {...(process.env.NEXT_PUBLIC_CRISPSTATS_DEBUG === "1" ? { "data-debug": "" } : {})}
  strategy="afterInteractive"
/>
```

Set `NEXT_PUBLIC_CRISPSTATS_DEBUG=1` in `.env.development.local` and in your test runs, never in production. [Localhost and testing](https://docs.crispstats.com/tracking/localhost-and-testing.md) shows a Playwright test that asserts on these lines.

## Report AI crawlers from proxy.ts

AI crawlers such as GPTBot and ClaudeBot do not run JavaScript, so the script never sees them. Your Next.js proxy (called middleware before Next.js 16) can report them to the collector. It sends only the crawler's User-Agent and the path: no IP address, no query string and no other header.

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

// AI crawlers do not run JavaScript, so this reports their visits from the server.
const AI_CRAWLERS =
  /GPTBot|OAI-SearchBot|ChatGPT-User|ClaudeBot|Claude-SearchBot|Claude-User|PerplexityBot|Perplexity-User|Google-Extended|GoogleOther|Applebot-Extended|Amazonbot|Bytespider|CCBot|meta-externalagent|meta-externalfetcher|MistralAI-User|DuckAssistBot|cohere-ai|YouBot/i;

export function proxy(request: NextRequest, event: NextFetchEvent) {
  const ua = request.headers.get("user-agent") ?? "";
  if (AI_CRAWLERS.test(ua)) {
    event.waitUntil(
      fetch("https://in.crispstats.com/bot", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ k: "cs_pk_xxxxxxxx", ua, path: request.nextUrl.pathname }),
      }).then(
        () => undefined,
        () => undefined,
      ),
    );
  }
  return NextResponse.next();
}

// Skip static files and the CrispStats proxy path.
export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico|k3x9qe/).*)"],
};
```

On Next.js 15 and earlier, name the file `middleware.ts` and the function `middleware`. If you already have a proxy, add the `if` block to it. Ordinary requests make no network call. The collector checks the User-Agent again and records only known AI crawlers. See [AI crawlers](https://docs.crispstats.com/ai/ai-crawlers.md) and the [`/bot` reference](https://docs.crispstats.com/api-reference/collector#post-/bot).

## Next steps

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

> [card] [Visitor id at checkout](https://docs.crispstats.com/revenue/visitor-id-at-checkout.md)
>
> Pass the visitor id to Stripe to attribute revenue.

> [card] [Single-page apps](https://docs.crispstats.com/tracking/single-page-apps.md)
>
> How navigation is seen, and manual pageviews.


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