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

# Send events from your server

> Send CrispStats custom events, revenue and identify calls from a webhook, cron or background job with one POST to the collector and a secret cs_sk_ key. Payload, curl and status codes.

Some actions happen where no browser is involved: a subscription renews, a webhook arrives, a background job finishes. To count them, send the event from your server with one `POST` to `https://in.crispstats.com/e`, authenticated by a secret API key (`cs_sk_…`). Pass the visitor id you saved from the browser, and the event joins that visitor's history. There is nothing to install: any HTTP client works.

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -X POST https://in.crispstats.com/e \
  -H "Authorization: Bearer $CRISPSTATS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"k":"cs_pk_xxxxxxxx","t":"event","n":"subscription_renewed","u":"","p":{"plan":"pro"},"vid":"0123456789abcdef0123456789abcdef","i":"user_42"}'
```

Unlike browser events, server-side events get a real status code back, so you can tell when one was rejected. Server-side custom events count toward your plan like any other custom event; `identify` and `revenue` do not.

## Set it up

**1. Create a secret API key**

In the dashboard, open the workspace page (**Workspace** in the account menu, or **Team and API keys** below a site's settings tabs), and under **API keys** create a key with the **Events** scope. The **Write** and **Admin** scopes also allow sending events; a **Read** key, the default for the REST API, gets `403 key_not_valid_for_site`. Choose whether the key works for every site in the workspace or only this site. Owners and admins can create keys.

The key is shown once. Store it as a secret on your server, for example in a `CRISPSTATS_API_KEY` environment variable. Never send it to a browser.

**2. Save the visitor id in the browser**

Server-side events attach to a visit only through a visitor id. When the user does something your server will follow up on, such as signing up or starting a checkout, read the id in the browser and send it to your backend:

```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
const visitorId = await crispstats.id();

await fetch("/api/signup", {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({ email, visitorId }),
});
```

`crispstats.id()` returns a Promise of the anonymous id the collector files this browser's events under right now. It resolves to `undefined` when the script did not start on the page (for example on `localhost` or in an opted-out browser) or when the request fails. Store the id with the user or order record. Behind a [proxy](https://docs.crispstats.com/tracking/proxy.md), `crispstats.id()` works the same way.

**3. Send the event from your server**

Post the event where the action happens. In TypeScript, this function is all you need. It runs on Node 18 and later, Cloudflare Workers, Vercel Functions, Deno and Bun:

```ts crispstats-server.ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// Sends a custom event to CrispStats from your server. Never import this in browser code.
export async function sendCrispStatsEvent(event: {
  name: string;
  props?: Record<string, string | number | boolean | null>;
  visitorId?: string; // saved earlier from crispstats.id()
  userId?: string; // your own user id
}): Promise<void> {
  const response = await fetch("https://in.crispstats.com/e", {
    method: "POST",
    headers: {
      authorization: `Bearer ${process.env.CRISPSTATS_API_KEY}`,
      "content-type": "application/json",
    },
    body: JSON.stringify({
      k: "cs_pk_xxxxxxxx",
      t: "event",
      n: event.name,
      u: "",
      p: event.props,
      vid: event.visitorId,
      i: event.userId,
    }),
  });
  if (response.status !== 202) {
    console.warn("CrispStats rejected the event", response.status, await response.text());
  }
}
```

Call it from your handler:

```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
await sendCrispStatsEvent({
  name: "subscription_renewed",
  props: { plan: subscription.plan },
  visitorId: subscription.visitorId,
  userId: subscription.userId,
});
```

Other languages send the same request: see [send the request over HTTP](#send-the-request-over-http).

**4. Check the dashboard**

Open **Events**. The event appears with the name and properties you sent.

## Send the request over HTTP

The request is the same from any language:

```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -X POST https://in.crispstats.com/e \
  -H "Authorization: Bearer $CRISPSTATS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"k":"cs_pk_xxxxxxxx","t":"event","n":"subscription_renewed","u":"","p":{"plan":"pro"},"vid":"0123456789abcdef0123456789abcdef"}'
```

```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import os
import requests

response = requests.post(
    "https://in.crispstats.com/e",
    headers={"Authorization": f"Bearer {os.environ['CRISPSTATS_API_KEY']}"},
    json={
        "k": "cs_pk_xxxxxxxx",
        "t": "event",
        "n": "subscription_renewed",
        "u": "",
        "p": {"plan": "pro"},
        "vid": "0123456789abcdef0123456789abcdef",
    },
    timeout=5,
)
if response.status_code != 202:
    print(response.status_code, response.json())
```

```js Node.js theme={"theme":{"light":"github-light","dark":"github-dark"}}
const response = await fetch("https://in.crispstats.com/e", {
  method: "POST",
  headers: {
    authorization: `Bearer ${process.env.CRISPSTATS_API_KEY}`,
    "content-type": "application/json",
  },
  body: JSON.stringify({
    k: "cs_pk_xxxxxxxx",
    t: "event",
    n: "subscription_renewed",
    u: "",
    p: { plan: "pro" },
    vid: "0123456789abcdef0123456789abcdef",
  }),
});
if (response.status !== 202) console.error(response.status, await response.json());
```

> [!WARNING]
>
> The header must start with exactly `Bearer cs_sk_`. A request without it is treated as a browser event: it gets an empty `202` even when the event is dropped, and a server's User-Agent (curl, Node, Python and similar clients) gets it filtered out as a bot. If every request returns `202` but no event appears, check the header.

### Request body

The body is JSON, at most 16 KB, in the same format the browser script sends.

| Field | Type | Required | Description |
| - | - | - | - |
| `k` | string | Yes | The site's public key, `cs_pk_…`. |
| `t` | string | Yes | `event` for a custom event, `revenue` for a payment, or `identify` to attach traits to a user. Other types are rejected. |
| `u` | string | Yes | The related page URL, up to 2,048 characters. Send `""` when there is none. |
| `n` | string | No | Event name, up to 120 characters. |
| `p` | object | No | Flat properties. Keys up to 60 characters; values are strings up to 500 characters, numbers, booleans or `null`. Up to 40 are kept. For `identify`, these are the user's traits. |
| `vid` | string | No | Visitor id from `crispstats.id()`: 32 lowercase hexadecimal characters. Any other value up to 64 characters is treated as no visitor id; a longer value fails validation. |
| `i` | string | No | Your user id, up to 200 characters. |
| `a` | integer | No | Revenue amount in minor units. Counted on `revenue` and `event` types. |
| `c` | string | No | ISO 4217 currency code. It must be exactly three characters or the request fails validation. Without it, or when the three characters are not letters, the site's currency is used. |
| `ts` | integer | No | Accepted, but the collector timestamps the event when it arrives. You cannot backdate events. |

### How the event is attributed

* **With a valid `vid`.** If that visitor has an open session, the event joins it and takes the session's source, and the session's user id when you send none. Otherwise the event is stored under that visitor id on its own, with the source **Direct**.
* **With `i` and no `vid`.** The event is filed under a visitor id derived from your user id, so repeated events for the same user land together, and it counts toward that user's identified profile.
* **With neither.** The event is counted, under an id of its own, but belongs to no visit.

Server-side events carry no location, browser or OS, and are recorded with the device type desktop: CrispStats does not use your server's IP address or User-Agent.

## Status codes

| Status | Body | Meaning |
| - | - | - |
| `202` | Empty | Accepted. A site that is paused or suspended also gets `202`, but the event is not stored. |
| `400` | `{"error":"invalid_json"}` | The body is not a JSON object. |
| `400` | `{"error":"invalid_payload","fields":["n"]}` | A field failed validation. `fields` lists up to 10 offending fields, such as `n` for a name over 120 characters, `p.plan` for a long value or `t` for an unknown type. |
| `400` | `{"error":"unsupported_event_type"}` | `t` is a type the browser script sends, such as `pageview` or `ping`. Server-side events accept only `event`, `revenue` and `identify`. |
| `401` | `{"error":"invalid_api_key"}` | The key is unknown, revoked, expired or malformed. |
| `403` | `{"error":"key_not_valid_for_site"}` | The key is valid but cannot send events for this site: no site has the public key in `k`, the key lacks the `events`, `write` or `admin` scope, it is limited to another site, or the site belongs to another workspace. |
| `413` | `{"error":"payload_too_large"}` | The body is over 16 KB. |
| `429` | `{"error":"rate_limited"}` | Too many server-side events for this site. The limit is 6,000 requests per 60 seconds per site, counted separately in each edge location. Retry later. |
| `503` | `{"error":"temporarily_unavailable"}` | The key could not be verified right now. Retry with backoff. |

## Next steps

> [card] [Visitor id at checkout](https://docs.crispstats.com/revenue/visitor-id-at-checkout.md)
>
> Pass the visitor id to your payment provider so revenue is attributed.

> [card] [API keys](https://docs.crispstats.com/account/api-keys.md)
>
> Create, scope, revoke and delete secret keys.

> [card] [Collector reference](https://docs.crispstats.com/api-reference/collector.md)
>
> Every endpoint the collector serves at in.crispstats.com.


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