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

# Proxy CrispStats through a Next.js route handler

> Serve the CrispStats script and events from your own domain in a Next.js app with one route handler. Works on Vercel, Node and Cloudflare (OpenNext, vinext).

To proxy CrispStats in a Next.js app, add one route handler at `app/k3x9qe/[...path]/route.ts` that forwards everything under that path to `https://in.crispstats.com/p/`, then point the script tag at the path with `data-api`. Ad blockers that stop known analytics hosts then see a request to your own domain, so those visitors are counted.

The handler is the same on Vercel, on Node and on Cloudflare with OpenNext (`@opennextjs/cloudflare`) or vinext. It forwards only the headers analytics needs and the visitor's address, never their cookies. Use your own path instead of `/k3x9qe`: **Settings**, **Tracking code**, **Proxy through your own domain** proposes one for your site and fills it into this code. See [the proxy overview](https://docs.crispstats.com/tracking/proxy.md) for how the path, the check and signing work on every host.

## Set up the proxy

**1. Add the route handler**

Create the file at `app/k3x9qe/[...path]/route.ts` (`src/app/k3x9qe/[...path]/route.ts` if you use a `src` folder). The folder name is your path, so it must start with a letter: Next.js does not route folders that start with `_`. Nothing goes in `next.config.ts`.

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

**2. Keep proxy.ts away from the path**

If your `proxy.ts` (or `middleware.ts`) runs on every path, leave `/k3x9qe` out of its matcher, so sign-in redirects and other logic never touch these requests.

> [!WARNING]
>
> Do not use `rewrites()` in `next.config.ts` for this. A rewrite to another host forwards every request header, including your visitors' login cookies.

**3. Point the script tag at the path**

`src` loads the script from your domain, and `data-api` sends events and visitor id requests to the same path:

```html HTML theme={"theme":{"light":"github-light","dark":"github-dark"}}
<script
  defer
  data-site="cs_pk_xxxxxxxx"
  data-domains="example.com"
  data-api="/k3x9qe"
  src="/k3x9qe/d.js"
></script>
```

```tsx Next.js 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"
/>
```

`data-api` is required. Without it the script sends events to `/e` on your own domain, and those requests fail. In JSX a flag attribute takes an empty string: `data-outbound=""`.

**4. Deploy and run the setup check**

Deploy, then open the check through your proxy, in a browser, on your own site:

```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
https://example.com/k3x9qe/check?k=cs_pk_xxxxxxxx
```

A working proxy answers like this:

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "ok": true,
  "version": "0.1.0",
  "site": "known",
  "proxied": true,
  "visitorAddressForwarded": true,
  "signed": false,
  "signatureRequired": false,
  "cookiesForwarded": false,
  "location": { "source": "proxy", "country": "PT" },
  "hostnames": ["example.com", "*.example.com"]
}
```

`"visitorAddressForwarded": true` and `"cookiesForwarded": false` are the two values that matter most. The [proxy overview](https://docs.crispstats.com/tracking/proxy.md#check-it-works) explains every field.

## Visitor address and location

The handler takes the visitor's address from `cf-connecting-ip` on Cloudflare, then `x-real-ip` (Vercel and most hosts), then the first `x-forwarded-for` entry, and sends it as `x-forwarded-for`. The collector uses it for the daily visitor hash and your excluded IP addresses, then discards it.

For location, it passes Vercel's `x-vercel-ip-country`, `x-vercel-ip-country-region` and `x-vercel-ip-city`, or Cloudflare's `cf-ipcountry`, `cf-region-code` and `cf-ipcity`, as the `x-crispstats-country`, `x-crispstats-region` and `x-crispstats-city` headers. On Cloudflare, turn on the **Add visitor location headers** managed transform for your zone to pass the region and city too. On a host that sends none of these, the collector looks the country, region and city up from the visitor's address itself.

## Sign the requests (optional)

Signing proves a forwarded request came from your proxy. Reveal the secret (`cs_px_…`) in **Settings**, **Tracking code**, **Proxy through your own domain**, **Advanced: sign proxied requests**, then give it to your host as `CRISPSTATS_PROXY_SECRET`. The handler sends it when it is set.

| Host | Where the secret goes |
| - | - |
| Vercel, Node and most hosts | `CRISPSTATS_PROXY_SECRET` in your host's environment variables, then redeploy. |
| Cloudflare with OpenNext or vinext | `npx wrangler secret put CRISPSTATS_PROXY_SECRET`, then redeploy. |

Open the setup check again and look for `"signed": true`. See [sign proxied requests](https://docs.crispstats.com/tracking/proxy.md#sign-proxied-requests).

## FAQ

> [accordion] Why not a rewrite in next.config.ts?
>
> A rewrite to another host forwards every request header, including your visitors' cookies. The route handler copies only the headers listed in `FORWARD`.

> [accordion] Does it work with the Pages Router?
>
> The route handler needs the `app` folder. An app that otherwise uses the Pages Router can still add this one file under `app/`.

> [accordion] Does crispstats.id() work behind the proxy?
>
> Yes. It asks `/k3x9qe/id`, which the same handler forwards. See [the visitor id behind a proxy](https://docs.crispstats.com/tracking/proxy.md#the-visitor-id-behind-a-proxy).

## Next steps

> [card] [Proxy overview](https://docs.crispstats.com/tracking/proxy.md)
>
> The path, the check, caching, limits and signing.

> [card] [Next.js install](https://docs.crispstats.com/install/nextjs.md)
>
> The script element for the root layout.

> [card] [Ad blockers](https://docs.crispstats.com/help/ad-blockers.md)
>
> What a proxy recovers and what it does not.


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