
# Track events

Send product events (page views, sign-ups, the features people use) with your product's public **ingest key** (`ik_…`). You'll find the key in **Settings → Connections → Send your own events**, next to copy-ready code for your website, curl and Node.js. The key can only write events, never read anything, so it's safe in frontend code.

The npm packages described further down (`@volae/js`, `@volae/node`, `@volae/better-auth`) aren't published. Use the script tag or plain HTTP instead.

## Script tag

```html
<script src="https://api.volae.net/sdk.js"></script>
<script>
  const volae = Volae.init({ key: "ik_…" }); // page views are recorded automatically
</script>
```

`volae.track(name, properties)`, `identify`, `page` and `reset` work as described under @volae/js below.

## Raw HTTP

```bash
curl https://api.volae.net/api/v1/events \
  -H "Authorization: Bearer ik_…" \
  -H "Content-Type: application/json" \
  -d '{ "events": [ { "eventId": "evt_8f2a", "name": "exported_pdf", "anonymousId": "…", "properties": { "pages": 40 } } ] }'
```

`eventId` is your own unique id (duplicates are dropped). Identify the person with `userId`, `email` or `anonymousId`; a public ingest key only links events to people Volae already knows, it never creates them. Up to 100 events per request and 8 KB of properties per event.

## AI crawler visits

Count visits from AI crawlers (GPTBot, OAI-SearchBot, ClaudeBot, PerplexityBot and others) with the same ingest key. Send one request per crawler visit from your server or middleware; **GEO → AI crawler visits** has ready-to-paste Next.js and Express snippets with your key in them.

```bash
curl https://api.volae.net/api/v1/crawler-hits \
  -H "Authorization: Bearer ik_…" \
  -H "Content-Type: application/json" \
  -d '{ "ua": "Mozilla/5.0 (compatible; GPTBot/1.4)", "path": "/pricing", "ip": "203.0.113.7", "status": 200 }'
```

Send `ua` and `path`; `ip` (the crawler's address) and `status` are optional, or batch up to 100 as `{ "hits": [ … ] }`. Requests whose user agent isn't a known AI crawler are ignored. The IP is checked against the crawler's published ranges and then dropped: only daily totals per crawler, page and status are kept. Claims whose IP doesn't match are counted apart as impostors.

## From your server: create people and record payments

The public key can't create people. To send people, subscriptions and payments from your backend, add a **Webhook** data source in **Settings → Connections**. It gives you a webhook URL and a signing secret (`whsec_…`); keep the secret on the server.

Send a JSON body `{ "id": "<batch id>", "records": [ … ] }` (up to 500 records, 1 MB) and sign it: `X-Volae-Signature: t=<unix seconds>,v1=<hex>`, where `v1` is HMAC-SHA256 of `"<t>.<raw body>"` keyed with the whole secret, `whsec_` prefix included. Requests more than 5 minutes off are rejected; resending the same batch id is safe.

```js
// Node 20+, Bun, Deno or Workers. No package needed.
import { createHmac } from "node:crypto";

const url = "https://api.volae.net/webhooks/in/…"; // from Settings → Connections
const secret = "whsec_…"; // load it from your server's environment

const body = JSON.stringify({
  id: crypto.randomUUID(),
  records: [
    { type: "person", ref: { externalId: "user_123", email: "ana@uni.edu" }, name: "Ana Lee", createdAt: new Date().toISOString() },
    { type: "event", eventId: "evt_8f2a", name: "exported_pdf", occurredAt: new Date().toISOString(), person: { externalId: "user_123" } },
  ],
});
const t = Math.floor(Date.now() / 1000);
const v1 = createHmac("sha256", secret).update(`${t}.${body}`).digest("hex");
await fetch(url, { method: "POST", headers: { "content-type": "application/json", "x-volae-signature": `t=${t},v1=${v1}` }, body });
```

The record types (`person`, `event`, `subscription`, `payment`) and their fields are listed in the @volae/node reference below; the package just builds and signs these requests for you.


---

# @volae/js

Browser SDK for [Volae](https://volae.net). Tracks product events, anonymous visitors and first-touch UTM from your website or web app. No dependencies, about 2 KB gzipped.

## Install

This package isn't published to npm. Load the script that Volae's API serves instead:

```html
<script src="https://api.volae.net/sdk.js"></script>
<script>
  const volae = Volae.init({ key: "ik_…" }); // your product's public ingest key
</script>
```

Your product's ingest key, with this snippet ready to copy, is in **Settings → Connections → Send your own events**. The ingest key can only write events, so it is safe to ship in frontend code. It cannot create people: Volae links events to a person once your server identifies them (see below).

## Usage

```ts
volae.track("exported_pdf", { pages: 40 }); // record an event
volae.identify("user_123");                 // after sign-in: later events carry your user id
volae.page();                               // record a page view ($pageview)
volae.reset();                              // on sign-out: forget the user id, start a new anonymous id
volae.getAnonymousId();                     // pass this to your server when the visitor signs up
```

`identify()` only remembers the id in the browser. It sends nothing and creates nobody. To create or update the person (email, name, plan), call `identify` from your server with [`@volae/node`](events.md#volaenode) or install [`@volae/better-auth`](events.md#volaebetter-auth), and pass the anonymous id along. Volae then attaches the visitor's earlier anonymous events and first-touch UTM to that person.

## Options

| Option | Default | |
|---|---|---|
| `key` | required | Public ingest key (`ik_…`) |
| `apiUrl` | `https://api.volae.net` | |
| `autoPageview` | `true` | Record a page view on init |
| `trackRouteChanges` | `false` | Record a page view when a single-page app changes path or query (pushState, replaceState, back/forward) |
| `respectDnt` | `true` | When Global Privacy Control or Do Not Track is on, store nothing and send anonymous counts only |
| `cookieDomain` | current host | Set to `example.com` to share the `volae_aid` cookie with `api.example.com` |

## What it stores and sends

- `localStorage.volae_aid` and a first-party cookie `volae_aid` (SameSite=Lax, 1 year): a random anonymous id. Your server can read the cookie; the Better Auth plugin does this automatically.
- `localStorage.volae_uid`: the id you passed to `identify()`.
- `localStorage.volae_ft`: first touch — `utm_*` from the landing URL, `document.referrer` and the landing page. Sent with every event.
- Every event also gets `$url`, `$referrer`, `$screen`, `$locale` and `$tz` properties. Your own properties win on conflicts.

If `localStorage` is unavailable (private mode, sandboxed iframes) the SDK keeps these in memory for the page's lifetime.

## Delivery

Events are queued and sent every second, or as soon as 20 are waiting (at most 100 per request). Rate limits (`429`) are retried after `Retry-After`; server errors and network failures are retried with exponential backoff, up to 5 times. Other rejections are dropped with one `console.warn`. The queue holds at most 500 events.

When the page is hidden or closed, whatever is left is sent with `navigator.sendBeacon`. Every event has a unique `eventId`, so a retried or re-sent event is recorded once.

Events with an empty or over-100-character name, or properties over 8 KB as JSON, are dropped with a warning.

## Server-side rendering

`Volae.init()` returns a no-op client when there is no `window`, so importing it in server code does not throw. Call `init` in the browser.


---

# @volae/node

Server SDK for [Volae](https://volae.net). Identify people, track events, and record subscriptions and payments from your backend. Runs on Node 20+, Bun, Deno and Cloudflare Workers (only `fetch` and Web Crypto). No dependencies.

## Install

This package isn't published to npm yet. Until it is, send the same calls as plain HTTP: the webhook format and copy-ready curl and Node.js examples are on the [Track events](https://api.volae.net/docs/events.md) page and in **Settings → Connections → Send your own events**. The rest of this README describes the package's API for when it ships.

In Volae, add a Webhook data source under **Settings → Connections** to get your webhook URL and signing secret. Keep the secret on the server.

```ts
import { Volae } from "@volae/node";

const volae = new Volae({
  webhookUrl: process.env.VOLAE_WEBHOOK_URL!, // https://api.volae.net/webhooks/in/…
  secret: process.env.VOLAE_WEBHOOK_SECRET!,  // whsec_…
});
```

## Usage

```ts
// Create or update a person
await volae.identify({
  userId: "user_123",
  email: "ana@uni.edu",
  name: "Ana Lee",
  anonymousId: req.cookies.volae_aid, // from @volae/js: links earlier anonymous visits and first-touch UTM
  traits: { plan: "pro" },
  createdAt: user.createdAt,
});

// Record an event
await volae.track({ userId: "user_123", event: "exported_pdf", properties: { pages: 40 } });

// Billing systems without a native Volae connector (Paddle, …)
await volae.subscription({
  externalId: "sub_123",
  customer: { userId: "user_123" },
  status: "active",
  plan: "Pro",
  mrrMinor: 2900, // monthly amount in cents; yearly plans ÷ 12
  currency: "usd",
  interval: "month",
});
await volae.payment({ externalId: "txn_456", customer: { userId: "user_123" }, status: "paid", amountMinor: 2900, currency: "usd" });

// Before the process exits
await volae.flush();
```

Dates accept a `Date`, an ISO string or epoch milliseconds. `track` generates a UUID `eventId` when you don't pass one; passing your own makes repeated sends of the same event harmless.

## Batching and delivery

By default records are queued and sent every 2 seconds, or as soon as 50 are waiting. Each request carries a batch id; retries reuse it, so Volae records a retried batch once. Rate limits (`429`) wait for `Retry-After`; server errors and network failures back off exponentially, up to 5 retries. `400` (bad signature or format), `404` (unknown webhook URL — the connection was removed) and other client errors are not retried.

| Option | Default | |
|---|---|---|
| `batch` | `true` | `false` sends every call right away and resolves once Volae accepted it |
| `flushAt` | `50` | Send when this many records are queued (max 500) |
| `flushInterval` | `2000` | Milliseconds before queued records are sent |
| `maxRetries` | `5` | |
| `timeout` | `10000` | Per-request timeout in milliseconds |
| `onError` | — | Receives every `VolaeError`. When set, no method throws |
| `fetch` | global `fetch` | |

Errors: without `onError`, direct sends (`batch: false`) and `flush()` reject with a `VolaeError` (`code`, `status`, `records`); failures of background batches are logged with `console.error`. In batch mode, `identify`/`track`/… never reject — invalid input is reported instead, so a forgotten `await` cannot crash your process.

### Serverless

On Cloudflare Workers, Vercel or Lambda the process may freeze right after the response. Either use `batch: false` and `await` each call, or keep batching and hand the flush to the platform:

```ts
ctx.waitUntil(volae.flush()); // Cloudflare Workers
```

## Verifying signatures

The same signing scheme is used for webhooks Volae receives:

```
X-Volae-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>
```

```ts
import { sign, verifySignature } from "@volae/node";

const header = await sign(secret, rawBody);            // build the header for a body you send yourself
const ok = await verifySignature(secret, header, rawBody); // false if wrong or older than 5 minutes
```

## Advanced: `sendBatch`

`volae.sendBatch(records, { id })` sends up to 500 raw records in one request, bypassing the queue, and throws on failure. Use a deterministic `id` for backfills so a re-sent batch is ignored.


---

# @volae/better-auth

[Better Auth](https://www.better-auth.com) plugin for [Volae](https://volae.net). Sends sign-ups, sign-ins and profile changes to Volae as they happen, and can sync your existing users once.

## Install

This plugin isn't published to npm yet. Until it is, connect Better Auth the other way: add a **Webhook** data source in Volae and call it with plain HTTP from Better Auth's `databaseHooks` when a user is created or updated (format and examples on [Track events](https://api.volae.net/docs/events.md)). The rest of this README describes the plugin for when it ships.

In Volae, add a data source under **Settings → Connections** to get your webhook URL and signing secret.

```ts
import { betterAuth } from "better-auth";
import { volae } from "@volae/better-auth";

export const auth = betterAuth({
  // …
  plugins: [
    volae({
      webhookUrl: process.env.VOLAE_WEBHOOK_URL!,
      secret: process.env.VOLAE_WEBHOOK_SECRET!,
      syncExistingUsers: true,
    }),
  ],
});
```

**With `syncExistingUsers: true`, run the migration before deploying:**

```bash
npx auth@latest migrate   # or: npx auth@latest generate, for Prisma / Drizzle
```

It adds one small table, `volaeSync`, that records how far the sync got. Better Auth checks the schema on startup, and auth requests fail until the table exists.

## What it sends

| When | Sent to Volae |
|---|---|
| A user is created | the person (your user id, email, name, sign-up time) and a `signed_up` event |
| A session is created | a `signed_in` event; the person's last-seen time |
| A session is refreshed (about once a day while someone stays signed in) | the person's last-seen time |
| A user's email or name changes | the person again |
| First auth request after start, with `syncExistingUsers` | every existing user, 200 per request |

If the request carries the `volae_aid` cookie from [`@volae/js`](events.md), the person is linked to that visitor's earlier anonymous events and first-touch UTM.

Everything is sent in the background. If Volae is slow or down, sign-ups and sign-ins are not affected; failures are retried and then logged through Better Auth's logger (or your `onError`).

On serverless platforms, let Better Auth keep the function alive for background work:

```ts
import { waitUntil } from "@vercel/functions";

betterAuth({ advanced: { backgroundTasks: { handler: waitUntil } }, /* … */ });
```

## Syncing existing users

The sync starts with the first auth request after your server starts (not at import time, so builds and CLI commands don't trigger it). It pages through users by id, 200 at a time, and saves its position after each page:

- If it is interrupted, the next start continues from the last saved user.
- With several instances, only one syncs at a time.
- If you connect a different Volae data source (the webhook URL changes), it syncs again for the new one.
- If Volae rejects the request (wrong secret, removed connection), it stops and logs the reason until you restart.

## Options

| Option | Default | |
|---|---|---|
| `webhookUrl` | required | |
| `secret` | required | |
| `syncExistingUsers` | `false` | Sync existing users once (needs the `volaeSync` table) |
| `onError` | Better Auth logger | `(message, error) => void` |
| `fetch` | global `fetch` | |

Requires `better-auth` 1.7 or later.
