> ## 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 the CrispStats script through your own domain

> Serve the CrispStats script and collector from a path on your own domain with one forwarding rule for Next.js, Cloudflare, Vercel, Netlify or nginx, and check that it works.

Ad blockers stop requests to known analytics hosts, which hides part of your audience. To count those visitors, serve the CrispStats script and the event endpoint from a path on your own domain. One forwarding rule sends everything under that path to `https://in.crispstats.com/p/`, and the script tag points at the path with `data-api`.

| Your site | Forwards to | What it is |
| - | - | - |
| `/k3x9qe/d.js` | `https://in.crispstats.com/p/d.js` | The script |
| `/k3x9qe/e` | `https://in.crispstats.com/p/e` | Events |
| `/k3x9qe/id` | `https://in.crispstats.com/p/id` | The visitor id for [`crispstats.id()`](#the-visitor-id-behind-a-proxy) |
| `/k3x9qe/check` | `https://in.crispstats.com/p/check` | The [setup check](#check-it-works) |

All four come from the same rule: `/k3x9qe/*` to `https://in.crispstats.com/p/*`. The examples on this page use `/k3x9qe` and `example.com`; use your own path and domain.

> [!NOTE]
>
> The older setup with two rules, `/stats/d.js` to `/js/script.js` and `/stats/e` to `/api/event`, keeps working. You do not have to change it. See [the two-rule setup](#the-older-two-rule-setup) for what is different and why moving is worth it.

## Guides by host

Each host has its own page with the rule, the script tag, the setup check, where the visitor's address and location come from, and how to sign requests. This page covers what they share.

> [card] [Next.js](https://docs.crispstats.com/tracking/proxy/nextjs.md)
>
> A route handler. Vercel, Node and Cloudflare (OpenNext, vinext).

> [card] [Vercel](https://docs.crispstats.com/tracking/proxy/vercel.md)
>
> A route in `vercel.json`, for sites that are not Next.js.

> [card] [Netlify](https://docs.crispstats.com/tracking/proxy/netlify.md)
>
> An edge function.

> [card] [Cloudflare Worker](https://docs.crispstats.com/tracking/proxy/cloudflare.md)
>
> A Worker on one route of your zone.

> [card] [nginx](https://docs.crispstats.com/tracking/proxy/nginx.md)
>
> A `location` block.

> [card] [Caddy](https://docs.crispstats.com/tracking/proxy/caddy.md)
>
> A `handle_path` block in the Caddyfile.

## Choose a path

Use a short path that is unique to your site, not `/stats`, `/analytics` or `/tracking`: blockers can list a common path as easily as a host. **Settings**, **Tracking code**, **Proxy through your own domain** proposes one for each site, such as `/k3x9qe`, and fills it into every example there. It is derived from the site, so it never changes. Any other path works, as long as the rule and the script tag use the same one.

For a Next.js route handler, the path becomes a folder name, so start it with a letter: Next.js treats folders that start with `_` as private and does not route them. The proposed path always starts with a letter.

## Set up the proxy

**1. Forward the path to the collector**

Pick your host. Each example forwards only the request headers analytics needs and the visitor's address, never their cookies (see [what a proxy forwards](#what-a-proxy-forwards)).

> [tab] Next.js
>
> Create a route handler at `app/k3x9qe/[...path]/route.ts` (`src/app/k3x9qe/[...path]/route.ts` if you use a `src` folder). Nothing goes in `next.config.ts` or `next.config.mjs`.
>
> ```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 runs on Vercel, on Node and on any other host. It reads the visitor's address and, on Vercel and Cloudflare, their location. 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.

> [tab] Next.js on Cloudflare
>
> With OpenNext (`@opennextjs/cloudflare`) or vinext, use the same route handler at `app/k3x9qe/[...path]/route.ts`. It runs as is.
>
> ```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 };
> ```
>
> On Cloudflare the handler takes the visitor's address from `cf-connecting-ip` and the country from `cf-ipcountry`. To pass the region and city too, turn on the **Add visitor location headers** managed transform for your zone in the Cloudflare dashboard.

> [tab] Vercel
>
> For sites on Vercel that are not Next.js, add a route to `vercel.json`:
>
> ```json vercel.json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
>   "routes": [
>     {
>       "src": "/k3x9qe/(.*)",
>       "dest": "https://in.crispstats.com/p/$1",
>       "transforms": [
>         { "type": "request.headers", "op": "delete", "target": { "key": "cookie" } },
>         { "type": "request.headers", "op": "delete", "target": { "key": "authorization" } }
>       ]
>     }
>   ]
> }
> ```
>
> Vercel adds the visitor's address. The two transforms remove cookies and authorization before the request leaves. Vercel does not allow `routes` in the same file as `rewrites`, `redirects` or `headers`: if your `vercel.json` uses those, use a route handler or another server-side function instead.

> [tab] Netlify
>
> Create an edge function. A plain `_redirects` proxy would pass your visitors' cookies along, so this function picks the headers itself.
>
> ```ts netlify/edge-functions/crispstats.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.
> import type { Config, Context } from "@netlify/edge-functions";
>
> const PREFIX = "/k3x9qe/";
> 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"];
>
> export default async (request: Request, context: Context) => {
>   const url = new URL(request.url);
>   const headers = new Headers();
>   for (const name of FORWARD) {
>     const value = request.headers.get(name);
>     if (value) headers.set(name, value);
>   }
>   headers.set("x-forwarded-for", context.ip);
>   if (context.geo.country?.code) headers.set("x-crispstats-country", context.geo.country.code);
>   if (context.geo.subdivision?.code) headers.set("x-crispstats-region", context.geo.subdivision.code);
>   if (context.geo.city) headers.set("x-crispstats-city", encodeURIComponent(context.geo.city));
>   const secret = Netlify.env.get("CrispStats_PROXY_SECRET");
>   if (secret) headers.set("x-crispstats-proxy-secret", secret);
>
>   const upstream = await fetch(UPSTREAM + url.pathname.slice(PREFIX.length) + url.search, {
>     method: request.method,
>     headers,
>     body: request.method === "POST" ? await request.arrayBuffer() : undefined,
>   });
>   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 const config: Config = { path: "/k3x9qe/*" };
> ```
>
> Netlify gives the function the visitor's address and location, and it passes both on.

> [tab] Cloudflare Worker
>
> Deploy a Worker and add the route `example.com/k3x9qe/*` to it, in the zone that serves your site.
>
> ```js worker.js theme={"theme":{"light":"github-light","dark":"github-dark"}}
> // A Worker on the route example.com/k3x9qe/*. Sends only the headers below:
> // never your visitors' cookies or authorization.
> const PREFIX = "/k3x9qe/";
> 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"];
>
> export default {
>   async fetch(request, env) {
>     const url = new URL(request.url);
>     const headers = new Headers();
>     for (const name of FORWARD) {
>       const value = request.headers.get(name);
>       if (value) headers.set(name, value);
>     }
>     headers.set("x-forwarded-for", request.headers.get("cf-connecting-ip") ?? "");
>     const { country, regionCode, city } = request.cf ?? {};
>     if (country && country !== "XX" && country !== "T1") headers.set("x-crispstats-country", country);
>     if (regionCode) headers.set("x-crispstats-region", regionCode);
>     if (city) headers.set("x-crispstats-city", encodeURIComponent(city));
>     if (env.CrispStats_PROXY_SECRET) headers.set("x-crispstats-proxy-secret", env.CrispStats_PROXY_SECRET);
>
>     const script = request.method === "GET" && url.pathname.endsWith(".js");
>     const upstream = await fetch(UPSTREAM + url.pathname.slice(PREFIX.length) + url.search, {
>       method: request.method,
>       headers,
>       body: request.method === "POST" ? request.body : undefined,
>       // The script is the same for a day: keep it in this zone's cache.
>       cf: script ? { cacheEverything: true, cacheTtl: 86400 } : undefined,
>     });
>     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 });
>   },
> };
> ```
>
> The Worker passes the visitor's address, country, region and city, and keeps the script in your zone's cache for a day.

> [tab] nginx
>
> Add this block inside the `server` block of your site, then reload nginx.
>
> ```nginx nginx.conf theme={"theme":{"light":"github-light","dark":"github-dark"}}
> location ^~ /k3x9qe/ {
>   proxy_pass https://in.crispstats.com/p/;
>   proxy_ssl_server_name on;
>   proxy_set_header Host in.crispstats.com;
>
>   # Only these headers go upstream: never your visitors' cookies or authorization.
>   proxy_pass_request_headers off;
>   proxy_set_header Content-Type $content_type;
>   proxy_set_header User-Agent $http_user_agent;
>   proxy_set_header Accept-Language $http_accept_language;
>   proxy_set_header Referer $http_referer;
>   proxy_set_header Origin $http_origin;
>   proxy_set_header If-None-Match $http_if_none_match;
>   proxy_set_header X-Forwarded-For $remote_addr;
> }
> ```
>
> Behind a load balancer, set `real_ip_header` (and `set_real_ip_from`) first, so `$remote_addr` is the visitor and not the load balancer. nginx does not know the visitor's location, so the collector looks the visitor's address up itself and you still get country, region and city. See [location](#location).

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

Replace the tag on your site. `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"
/>
```

Keep any other attributes you use, such as `data-outbound`. In JSX, a flag attribute takes an empty string: `data-outbound=""`. The dashboard shows the tag for your platform with your key, domain and path filled in.

`data-api` is required. Without it the script sends events to `/e` on the origin it was loaded from, which is your own domain, and those requests fail.

**3. Run the setup check**

Open the setup 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
```

It answers with JSON. A working proxy looks 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"]
}
```

Then open your site, filter the browser's network panel by `k3x9qe`, and check that `/k3x9qe/d.js` loads with `200` (or `304` once cached) and the `POST` to `/k3x9qe/e` gets `202`. Your visit appears in **Realtime** within a few seconds.

## Check it works

The setup check, `GET <your path>/check?k=<public key>`, tells you what the collector sees for a request that came through your proxy. It never shows an address. **Settings**, **Tracking code**, **Proxy through your own domain**, step 3 **Check it** runs the same check from the dashboard once the first event arrives, and lists what it found.

| Field | Good value | If not |
| - | - | - |
| `site` | `"known"` | The key in `k` is wrong. Copy it from **Settings**, **Tracking code**. |
| `proxied` | `true` | The request reached the collector directly: your rule redirects instead of forwarding, or it points at `/check` instead of `/p/check`. |
| `visitorAddressForwarded` | `true` | Your proxy does not set `x-forwarded-for` to the visitor's address, or sets a private one. Every visit then looks like your server, and visitors merge into one. Use the code above as it is. |
| `cookiesForwarded` | `false` | Your proxy forwards your visitors' cookies, login sessions included. Forward only the [listed headers](#what-a-proxy-forwards). |
| `signed` | `true`, or `false` when you do not sign | `null` means the request was not proxied. See [sign proxied requests](#sign-proxied-requests). |
| `signatureRequired` | Your choice | When `true`, an unsigned request counts as coming from your server. |
| `location.source` | `"proxy"` or `"lookup"` | `"proxy"`: your location headers arrived. `"lookup"`: no headers, so CrispStats looked the visitor's address up itself. `"timezone"` means the visitor's address did not arrive, so the country comes from the browser's timezone and region and city are empty. See [location](#location). |
| `hostnames` | Your domains | The hostnames the site accepts events from. Events from any other hostname are dropped. |

`ok` is `true` when the key is known, the visitor's address arrives, no cookies are forwarded and, if the site requires it, the request is signed.

> [!TIP]
>
> From the dashboard your browser sends no cookies to your site, so the dashboard cannot see cookie forwarding. Open the check in a tab on your own site, signed in as a user would be, and look for `"cookiesForwarded": false`.

A direct install has a check too: `https://in.crispstats.com/check?k=cs_pk_xxxxxxxx`. See the [collector reference](https://docs.crispstats.com/api-reference/collector.md#get-/check).

## What a proxy forwards

The collector needs only a few request headers. Every example on this page forwards exactly these, and nothing else:

| Request header | Why |
| - | - |
| `content-type` | How the event body is encoded. |
| `user-agent` | Part of the daily visitor hash, the browser and device, and bot filtering. |
| `accept-language`, `referer`, `origin` | Describe the visitor's request without identifying anyone. Safe to pass on. |
| `if-none-match` | Lets a cached script be revalidated with a `304`. |
| `x-forwarded-for` | Set by your proxy to the visitor's address. |

Never forward `cookie` or `authorization`. A proxy that copies all request headers, such as `new Headers(request.headers)` in a Worker or `rewrites()` in `next.config.ts`, sends your visitors' login cookies to a third party. The collector does not need them and the setup check reports them as `cookiesForwarded: true`.

From the collector's response, the examples pass back `content-type`, `cache-control`, `etag` and `access-control-allow-origin`. The last one lets the dashboard read your `/check` from another origin.

## The visitor address

Behind a proxy, every request reaches the collector from your server. CrispStats counts visitors with a [daily hash](https://docs.crispstats.com/privacy/cookieless-tracking.md) of the visitor's address and User-Agent, so the proxy has to pass the visitor's address along, in `x-forwarded-for`. The address is used for that hash and for your [excluded IP addresses](https://docs.crispstats.com/tracking/exclude-traffic.md#exclude-ip-addresses), then discarded. It is never stored.

On `/p` routes the collector takes the first public address in `x-forwarded-for`. Private addresses (such as `10.x.x.x` or `192.168.x.x`) and malformed entries are skipped. Without a public address it uses your server's address, and visitors on the same browser version merge into one. The direct routes, `/e` and `/id`, ignore `x-forwarded-for`.

Where each host gets the address:

| Host | Visitor address |
| - | - |
| Next.js route handler | `cf-connecting-ip` on Cloudflare, then `x-real-ip` (Vercel and most hosts), then the first `x-forwarded-for` entry. |
| Vercel `vercel.json` | Added by Vercel. |
| Netlify edge function | `context.ip`. |
| Cloudflare Worker | `cf-connecting-ip`. |
| nginx | `$remote_addr`. Behind a load balancer, configure `real_ip_header` first. |

To confirm it arrives, open the [setup check](#check-it-works) and look for `"visitorAddressForwarded": true`.

## Location

Without a proxy, the collector places a visitor from its own network edge. Behind a proxy that edge sees your server, so the collector places the visitor in one of three ways, in this order:

1. **Your location headers**, when your proxy sends them (below). They always win.
2. **The visitor's address.** When your proxy forwards the address in `x-forwarded-for` (every setup on this page does) and sends no location headers, the collector looks the address up in an IP-location database that CrispStats hosts itself. You get country, region, city and the point on the map with nothing to add to your code, behind any proxy, nginx and one-line rewrites included. The address is used for that lookup in memory only: it is never stored, and no third party receives it.
3. **The browser's timezone**, when neither arrived. That gives the country only.

A proxy that knows where the visitor is can still say so in three headers:

| Header | Value |
| - | - |
| `x-crispstats-country` | ISO 3166-1 alpha-2 code, such as `PT`. Required for the other two to count. |
| `x-crispstats-region` | Region code or name, up to 64 characters. Codes such as `CA` or `13` are stored as the region's English name (California, Tokyo) where CrispStats knows the code. |
| `x-crispstats-city` | City, up to 80 characters, percent-encoded as `encodeURIComponent` does. |

The Next.js handler, the Netlify function and the Cloudflare Worker above set them from what the host provides. The collector also reads Vercel's `x-vercel-ip-country`, `x-vercel-ip-country-region` and `x-vercel-ip-city` when a proxy passes them on. You do not need them for region and city any more; send them when your host knows the location, and they are used instead of the lookup.

The setup check shows where the location came from: `"location": { "source": "proxy" }` when your headers arrived, `"lookup"` when the collector looked the address up, `"timezone"` when neither was possible.

> [!NOTE]
>
> IP Geolocation by [DB-IP](https://db-ip.com). The database is DB-IP's IP to City Lite, licensed under CC BY 4.0 and refreshed monthly.

## The visitor id behind a proxy

`crispstats.id()` returns the visitor id you pass to your payment provider for [revenue attribution](https://docs.crispstats.com/revenue/visitor-id-at-checkout.md). Behind a proxy it asks `<data-api>/id`, which the one rule forwards to `/p/id`, so it works on every page, single-page apps included.

If the proxy does not answer with the expected JSON, for example with the older two-rule setup that forwards no `/id`, the script asks `https://in.crispstats.com/id` directly instead. Calling `https://in.crispstats.com/id?k=cs_pk_xxxxxxxx` yourself from the visitor's browser keeps working too. Both give the same id when your proxy forwards the visitor's address, unless a blocker stops the direct request.

## Script caching

The collector serves the script with `Cache-Control: public, max-age=86400, stale-while-revalidate=604800` and an `ETag`, and answers `304` to a matching `If-None-Match`. Every example passes `cache-control` and `etag` back and forwards `if-none-match`, so browsers cache the script for a day and then revalidate it cheaply.

The Cloudflare Worker also keeps the script in your zone's cache for a day (`cacheTtl: 86400`), so most script requests never leave your zone. Events, `/id` and `/check` are never cached. See [script builds](https://docs.crispstats.com/tracking/script-builds.md#caching-and-versions).

Under your path, any file name ending in `.js` serves the full script, so `/k3x9qe/app.js` works as well as `/k3x9qe/d.js`. `/k3x9qe/d.core.js` serves the [core build](https://docs.crispstats.com/tracking/script-builds.md).

## Rate limits behind a proxy

Proxied requests are never limited by your proxy's own address, so sites whose proxies share a host's outgoing addresses (on Vercel, Netlify or Cloudflare) do not share a limit. On `/p` routes, the collector counts by site and visitor address, 1,200 events a minute for one visitor, with a ceiling of 6,000 a minute for all proxied traffic of one site in each Cloudflare location. A direct `POST /e` is counted by the connecting address, 1,200 a minute. Requests signed with your [proxy secret](#sign-proxied-requests) skip the per-site ceiling, so forged unsigned traffic cannot crowd out your real visitors. See [collector limits](https://docs.crispstats.com/api-reference/rate-limits.md#collector-limits).

## Sign proxied requests

Signing is optional, and worth doing for any site with real traffic. It proves that a forwarded request came from your proxy, so nobody else can post events to your site's proxy routes with made-up visitor addresses or locations, and signed requests skip the per-site ceiling that forged traffic could otherwise fill.

**1. Reveal the proxy secret**

In **Settings**, **Tracking code**, **Proxy through your own domain**, open **Advanced: sign proxied requests** and select **Reveal**. Owners and admins can see it. The secret starts with `cs_px_`. Keep it on your server: never put it in the page.

**2. Give it to your proxy**

The code examples read it from an environment variable named `CrispStats_PROXY_SECRET` and send it as the `x-crispstats-proxy-secret` header when it is set.

| Host | Where the secret goes |
| - | - |
| Next.js, Netlify | `CrispStats_PROXY_SECRET` in your host's environment variables, then redeploy. |
| Next.js on Cloudflare, Cloudflare Worker | `npx wrangler secret put CrispStats_PROXY_SECRET`, then redeploy. |
| Vercel `vercel.json` | `CrispStats_PROXY_SECRET` in the project's environment variables, and the transform below in the route's `transforms`. |
| nginx | The line below in the `location` block, with your secret. |

```json Vercel transform theme={"theme":{"light":"github-light","dark":"github-dark"}}
{ "type": "request.headers", "op": "set", "target": { "key": "x-crispstats-proxy-secret" }, "args": "$CrispStats_PROXY_SECRET", "env": ["CrispStats_PROXY_SECRET"] }
```

```nginx nginx theme={"theme":{"light":"github-light","dark":"github-dark"}}
proxy_set_header x-crispstats-proxy-secret "<your proxy secret>";
```

**3. Check, then require it**

Open the [setup check](#check-it-works) and look for `"signed": true`. Then you can turn on **Only accept proxied events signed with this secret** in the same section. From then on, a request on a proxy route without a valid secret is treated as coming from your server: its forwarded address and location headers are ignored.

Without the switch, unsigned forwarding keeps working as before, and signed requests are trusted the same way.

## The older two-rule setup

Sites set up before the one-rule proxy forward two paths:

| Your path | Forwards to |
| - | - |
| `/stats/d.js` | `https://in.crispstats.com/js/script.js` |
| `/stats/e` | `https://in.crispstats.com/api/event` |

with the tag `data-api="/stats" src="/stats/d.js"`. This keeps working. `/api/event` takes the visitor from the first `x-forwarded-for` entry when it is a public address, and follows the same location headers, signing and per-visitor limits as `/p/e`. `crispstats.id()` falls back to the collector directly, because these rules forward no `/id`.

Moving to the one rule is worth it when:

* your rules are rewrites that copy every request header (`next.config.ts` rewrites, a Netlify `_redirects` proxy, a Worker that uses `new Headers(request.headers)`): they send your visitors' cookies to the collector,
* you want `/check` and `/id` through your own domain,
* your path is `/stats`, which blockers can list.

To move, deploy the new rule under a new path, switch the tag to that path, and remove the old rules once no cached page uses them.

## What else changes behind a proxy

* **Content Security Policy.** `'self'` covers the script and events. See [Content Security Policy](https://docs.crispstats.com/help/content-security-policy.md).
* **Excluded IP addresses** are compared with the forwarded visitor address. See [exclude traffic](https://docs.crispstats.com/tracking/exclude-traffic.md#exclude-ip-addresses).
* **Ad blockers** that list your path can still stop it. A path unique to your site makes that unlikely. See [ad blockers](https://docs.crispstats.com/help/ad-blockers.md).

## Next steps

> [card] [Ad blockers](https://docs.crispstats.com/help/ad-blockers.md)
>
> How blockers affect your counts and what a proxy recovers.

> [card] [Script builds](https://docs.crispstats.com/tracking/script-builds.md)
>
> Which file is which, caching and versions.

> [card] [Collector reference](https://docs.crispstats.com/api-reference/collector.md)
>
> Every route under /p and what it answers.


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