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

# Alert webhooks and signature verification

> CrispStats webhook channels POST signed JSON when an alert fires or recovers. Payload fields, headers, HMAC-SHA256 verification and deduplication, with code samples.

A webhook channel sends a signed JSON `POST` to your HTTPS endpoint every time an alert attached to it fires (`alert.triggered`) or recovers (`alert.recovered`). Each request carries an HMAC-SHA256 signature over a timestamp and the raw body, so your endpoint can prove the request came from CrispStats and is recent. This page covers the payload, the headers, how to verify the signature and how to handle retries.

Set up the channel and the alerts that use it in the dashboard; see [alert channels](https://docs.crispstats.com/alerts/channels.md).

> [!WARNING]
>
> CrispStats creates a signing secret (`whsec_…`) for every webhook channel when you add it, and signs every delivery with it. The dashboard does not show this secret yet, so you cannot verify signatures until it does. Until then, treat incoming requests as unverified: use an endpoint URL that is hard to guess and act only on what you can confirm in the dashboard.

## Endpoint requirements

| Requirement | Detail |
| - | - |
| Scheme and port | `https://` on the default port 443. |
| Host | A public host. URLs that point at, or resolve to, private, loopback, link-local or metadata addresses are refused, and so are URLs with a user name or password. |
| Answer | Any `2xx` status counts as delivered. Answer within 8 seconds. |
| Redirects | Not followed. A `3xx` answer counts as a failed delivery. |

## Events

| Event | Sent when |
| - | - |
| `alert.triggered` | An alert rule's condition is met. |
| `alert.recovered` | A rule that fired is back to normal, for example a monitor that was down is up again. |
| `alert.test` | Someone selects **Send test** on the channel in the alert settings. |

## Headers

| Header | Value |
| - | - |
| `Content-Type` | `application/json; charset=utf-8` |
| `User-Agent` | `CrispStats-Webhooks/1.0 (+https://crispstats.com/docs/alerts)` |
| `X-CrispStats-Event` | `alert.triggered`, `alert.recovered` or `alert.test`. |
| `X-CrispStats-Delivery` | A unique id for this alert firing and this channel. A retry of the same delivery carries the same id. |
| `X-CrispStats-Timestamp` | Unix seconds when the request was signed. |
| `X-CrispStats-Signature` | `v1=` followed by the hex HMAC-SHA256 of `{timestamp}.{raw body}`, keyed with the channel's signing secret. |

## Payload

The body is a JSON object. Fields under `message` are written for people and are the same text the email, Slack and Discord channels show; `data` carries the raw numbers behind the alert.

**id** `string` *required*

The delivery id, the same value as the `X-CrispStats-Delivery` header.

**type** `string` *required*

`alert.triggered`, `alert.recovered` or `alert.test`.

**createdAt** `string` *required*

When the alert fired, ISO 8601 UTC.

**site** `object` *required*

**properties**

**id** `string`

The site id. Empty on `alert.test`.

**name** `string`

The site name.

**domain** `string`

The site domain.

**alert** `object` *required*

**properties**

**id** `string`

The alert rule's id. `test` on `alert.test`.

**name** `string`

The rule's name as you set it.

**type** `string`

The rule type: `traffic_spike`, `traffic_drop`, `no_traffic`, `error_spike`, `new_error`, `vitals_regression`, `monitor_down`, `goal_completed`, `revenue_received`, `revenue_milestone`, `usage_limit`, or `test`.

**message** `object` *required*

**properties**

**title** `string`

The headline, also used as the email subject.

**summary** `string`

One or two sentences of context.

**facts** `object[]`

Label and value pairs, `{ "label", "value" }`, with the figures formatted.

**list** `object`

Present on some alerts, such as new error groups or completed goals: `{ "title", "items" }`, where `items` are label and value pairs.

**url** `string`

A link to the relevant dashboard screen.

**manageUrl** `string`

A link to where the alert is changed or muted.

**data** `object` *required*

The raw values that triggered the alert. Its fields depend on the rule type. `{ "test": true }` on `alert.test`.

This is the body of a test delivery, whose content is fixed:

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "id": "test.4c1d2e3f-5a6b-4c7d-8e9f-0a1b2c3d4e5f",
  "type": "alert.test",
  "createdAt": "2026-11-16T14:40:00.000Z",
  "site": { "id": "", "name": "CrispStats", "domain": "crispstats.com" },
  "alert": { "id": "test", "name": "Test notification", "type": "test" },
  "message": {
    "title": "Test notification from CrispStats",
    "summary": "This channel is set up. Alerts you attach to it will arrive here, with the numbers and a link to the dashboard.",
    "facts": [
      { "label": "Example", "value": "Traffic is 3.2× normal" },
      { "label": "Sent", "value": "2026-11-16 14:40 UTC" }
    ],
    "url": "https://crispstats.com/app",
    "manageUrl": "https://crispstats.com/app"
  },
  "data": { "test": true }
}
```

Alert deliveries have the same shape, with your site, rule and figures filled in.

## Verify the signature

**1. Read the raw body**

Read the request body as bytes before any JSON parsing. Parsing and re-serializing changes the bytes and breaks the signature.

**2. Check the timestamp**

Read `X-CrispStats-Timestamp`. Reject the request if it is more than 300 seconds away from your current time, in either direction. This stops an old request from being replayed.

**3. Compute the expected signature**

Compute HMAC-SHA256 with the channel's signing secret as the key, over the string `{timestamp}.{raw body}`: the timestamp, a full stop, then the body. Encode the result as lowercase hex.

**4. Compare in constant time**

`X-CrispStats-Signature` holds one or more `v1=<hex>` values separated by commas or spaces. Accept the request if any `v1` value equals your result, using a constant-time comparison.

**5. Deduplicate**

Store each `X-CrispStats-Delivery` id you have processed, and skip a request whose id you have seen. Then answer `200`.

Both samples below are complete servers on port 8080 that use only the standard library. They read the secret from `CRISPSTATS_WEBHOOK_SECRET`.

```javascript Node.js theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { createServer } from "node:http";
import { createHmac, timingSafeEqual } from "node:crypto";

const SECRET = process.env.CRISPSTATS_WEBHOOK_SECRET; // whsec_…
const TOLERANCE_SECONDS = 300;
const processed = new Set(); // use a database table in production

function verify(rawBody, headers) {
  const timestamp = Number(headers["x-crispstats-timestamp"]);
  if (!Number.isInteger(timestamp)) return false;
  if (Math.abs(Math.floor(Date.now() / 1000) - timestamp) > TOLERANCE_SECONDS) return false;

  const expected = createHmac("sha256", SECRET).update(`${timestamp}.`).update(rawBody).digest();
  const header = headers["x-crispstats-signature"] ?? "";
  return header.split(/[,\s]+/).some((part) => {
    const match = /^v1=([0-9a-f]{64})$/i.exec(part);
    return match !== null && timingSafeEqual(Buffer.from(match[1], "hex"), expected);
  });
}

createServer((req, res) => {
  const chunks = [];
  req.on("data", (chunk) => chunks.push(chunk));
  req.on("end", () => {
    const rawBody = Buffer.concat(chunks);
    if (req.method !== "POST" || !verify(rawBody, req.headers)) {
      res.writeHead(401).end();
      return;
    }
    const delivery = req.headers["x-crispstats-delivery"];
    if (!processed.has(delivery)) {
      processed.add(delivery);
      const payload = JSON.parse(rawBody.toString("utf8"));
      console.log(payload.type, payload.site.domain, payload.message.title);
    }
    res.writeHead(200).end();
  });
}).listen(8080);
```

```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import hashlib
import hmac
import json
import os
import re
import time
from http.server import BaseHTTPRequestHandler, HTTPServer

SECRET = os.environ["CRISPSTATS_WEBHOOK_SECRET"].encode()  # whsec_…
TOLERANCE_SECONDS = 300
processed = set()  # use a database table in production


def verify(raw_body: bytes, headers) -> bool:
    try:
        timestamp = int(headers.get("X-CrispStats-Timestamp", ""))
    except ValueError:
        return False
    if abs(int(time.time()) - timestamp) > TOLERANCE_SECONDS:
        return False

    expected = hmac.new(SECRET, f"{timestamp}.".encode() + raw_body, hashlib.sha256).hexdigest()
    for part in re.split(r"[,\s]+", headers.get("X-CrispStats-Signature", "")):
        if part.startswith("v1=") and hmac.compare_digest(part[3:].lower(), expected):
            return True
    return False


class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        raw_body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
        if not verify(raw_body, self.headers):
            self.send_response(401)
            self.end_headers()
            return
        delivery = self.headers.get("X-CrispStats-Delivery")
        if delivery not in processed:
            processed.add(delivery)
            payload = json.loads(raw_body)
            print(payload["type"], payload["site"]["domain"], payload["message"]["title"])
        self.send_response(200)
        self.end_headers()


HTTPServer(("", 8080), Handler).serve_forever()
```

In a framework, make sure you get the unparsed body: in Express use `express.raw({ type: "application/json" })` on the webhook route, and in Flask use `request.get_data()`.

## Retries and duplicates

* A `429` or `5xx` answer is retried once, after the `Retry-After` you send (seconds or an HTTP date) or after 1 second. If `Retry-After` is longer than 5 seconds, the delivery fails without a retry.
* A timeout or network error is not retried, because the request may have arrived. A `4xx` other than `429`, and any `3xx`, fail at once.
* If a delivery run is interrupted, the firing is picked up again later and sent with the same delivery id.

Because the same delivery can arrive more than once, always deduplicate on `X-CrispStats-Delivery`. Answer quickly and do slow work after responding, so you stay inside the 8-second timeout.

## Next steps

> [card] [Alert channels](https://docs.crispstats.com/alerts/channels.md)
>
> Add a webhook channel and send a test.

> [card] [Alert rule types](https://docs.crispstats.com/alerts/rule-types.md)
>
> What each rule type watches and when it fires.

> [card] [Alerts overview](https://docs.crispstats.com/alerts/overview.md)
>
> How alerts, cooldowns and recoveries work.


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