# Behave > Behave is Baobab Tech's usage analytics service. An app sends events from its own server to one route, `POST https://behave.baobabtech.app/api/v1/batch`, with a per-app write key, and reads its numbers back from `GET https://behave.baobabtech.app/api/v1/metrics` and `GET https://behave.baobabtech.app/api/v1/reports/` with a read key. The npm package `@baobabtech/behave` wraps both, and https://behave.baobabtech.app/llms-integrate.txt walks an agent through adding it to an app. Every other page at https://behave.baobabtech.app is a dashboard behind sign-in, so a fetch of the site shows a login page. The public surface is this file, the full reference at https://behave.baobabtech.app/llms-full.txt, the API under `/api/v1/` (key required) and the widget registry under `/r/`. This file is enough to send events; https://behave.baobabtech.app/llms-full.txt adds what each call writes, the metric response, every template and report, and the SDK in full. ## Authenticate ``` Authorization: Bearer : Content-Type: application/json ``` - The credential is one string, `:`. Keep it in a server environment variable: `BEHAVE_KEY=:` for a write key, `BEHAVE_READ_KEY` for a read key. - **A key has a scope.** `write`: `POST /api/v1/batch` and `POST /api/v1/forget`. `read`: `/api/v1/reports/*` and `/api/v1/metrics`. A key issued before scopes is `all` and does both. `GET /api/v1/me` takes any key. A key used outside its scope answers `403 wrong_scope`. - **Server side only**, both kinds. There is no public key. Never put a key in a `NEXT_PUBLIC_*` variable, a browser bundle or a mobile app. - A key is issued by an admin of the app in the Behave dashboard: https://behave.baobabtech.app//settings?tab=keys, **New key**, with a scope. The secret is shown once. An agent without a key asks the person it works for to issue one; it never invents one. - An app may hold several live keys: rotate by issuing a new one, deploying it, then revoking the old one. - **One Behave app per environment.** Production sends to `` with its key; preview and staging deployments send to a second app, `-staging`, with its own key; local development sets no key and sends nothing. On Vercel: `BEHAVE_KEY` in Production holds the production app's key, in Preview (and any custom staging environment) the staging app's. Test traffic then never moves a production number. ## Send events `POST /api/v1/batch` takes one call as a JSON object, an array of 1 to 500 calls, or `{ "batch": [ ... ] }`. Types may be mixed. | Field | Required | Meaning | |---|---|---| | `type` | Yes | `track`, `identify` or `group` | | `message_id` | Yes | The idempotency key, 8 to 200 characters | | `event` | `track` only | The event name (rule below) | | `user_id` | One of the two on `track`; required on `identify` | The app's stable id for the person: a database id or a hash, never an email or a name. At most 200 characters | | `anonymous_id` | One of the two on `track` | A client-generated id for a browser or session before sign-in. At most 200 characters | | `group_type`, `group_id` | Together or not at all; required on `group` | The container the user was in: `workspace` and its id. Each at most 200 characters | | `timestamp` | No | ISO 8601, when it happened. Defaults to arrival | | `release` | No, `track` only | The app version, 1 to 100 characters | | `surface` | No, `track` only | Where it happened: `web`, `api`, `mcp`. 1 to 100 characters | | `properties` | No, `track` only | A JSON object of small facts: counts, ids, booleans, short enums. Stored verbatim | | `traits` | No, `identify` and `group` only | A JSON object of slow-changing facts. Replaces the stored traits. Categories only: a role, a plan, an organisation, an email domain, a locale; never a person's name or email | Any other key is dropped without a warning. ### Event names Lowercase, dotted, at most 40 characters, matching `^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$`. - A noun then a past-tense verb: `document.opened`, not `openDocument` or `Document Opened`. - Low cardinality, never built from data: `document.opened`, never `document.4f21.opened`. Put the id in `properties`. - A page load fires `*.opened`; an action the user asked for fires `*.performed`. - Any name that matches is accepted. The app's event registry on the dashboard is documentation, not a gate: an unregistered name is stored and shown as "seen, not registered". - A registered event can have a **property list** (name and type: `string`, `number` or `boolean`), set by the app's admins; on a standard event (below) the list checks the types of its own properties and the app's, and any other property is kept. Then a property not on it, or of the wrong type, is dropped and named in that call's result as `dropped_properties`, with `"warning": "properties_dropped"`; an app set to strict refuses the call as `property_not_allowed` instead. ### Idempotency `message_id` is unique per app. **Sending the same call twice is a success and stores one row**, so a retry after a timeout is safe. Derive it from the act, not the attempt: the app's own event id, or `::`. A fresh uuid per retry defeats it. `identify` and `group` still need one. The two auth events, where a retry or a hook firing twice is likeliest: `signed_up:` and `signed_in:`. ### Time `timestamp` is the client's clock. Reports read `occurred_at`: the `timestamp` when it falls between 7 days before arrival and 5 minutes after, and the arrival time otherwise, with `"warning": "timestamp_clamped"` on that call's result. There is no backfill endpoint. All times are UTC. ### The six standard events Every app's registry starts with these, and the metric templates default to them. Use these exact names for these acts; name anything else in the same style. Their properties are defined by Behave: an app may send more of its own, listed or not. - `user.signed_up`: send on the server, once, where the account row is created. The activation, retention and new users templates start from it. - `user.signed_in`: send on the server, where the session is created. Never from the browser: it is the event a sign-in funnel starts from. - `page.viewed`: send when a page loads. Property `page` (string): a route pattern, never a URL with ids. - `search.performed`: send when a search the user asked for returns. Property `results` (number): the number of results. - `feature.used`: send when the user uses a named feature. The feature adoption template reads it. Property `feature` (string): a short fixed name. - `feedback.submitted`: send when the user rates something. The property average template reads it. Property `score` (number): the rating, a number. ### The response `202 Accepted`, one result per call, in order: ```json { "received": 2, "accepted": 1, "rejected": 1, "results": [ { "index": 0, "message_id": "search_9f21a4", "status": "accepted" }, { "index": 1, "message_id": "x_00000001", "status": "rejected", "error": "invalid_event_name", "message": "\"Search Performed\" is not a dotted lowercase name of at most 40 characters." } ] } ``` - A `202` means accepted for writing; the rows are written just after the response. A call accepted but not stored is counted as `failed` in ingest-health. - One bad call never refuses the others. A refused call is never written; fix it and send it again. - A duplicate `message_id` is `accepted`, not refused. - An accepted call can carry `warning` (`timestamp_clamped` or `properties_dropped`) and `dropped_properties`, the names removed. Log them: they are the event stored differently from how it was sent. ### Limits | Limit | Value | Over it | |---|---|---| | Calls per batch | 500 | `400 invalid_batch` | | Request body | 500 KB (512000 bytes) | `413 payload_too_large` | | One call, as JSON | 32 KB (32768 bytes) | that call: `event_too_large` | | Keys in `properties` or `traits` | 100 | that call: `too_many_properties` | | Any string value | 1024 characters | that call: `value_too_long` | | Event name | 40 characters, the regex above | that call: `invalid_event_name` | | `message_id` | 8 to 200 characters | that call: `invalid_message_id` | | `user_id`, `anonymous_id`, `group_type`, `group_id` | 1 to 200 characters | that call: `invalid_identity` | | `user_id` starting with `forgotten:` | Refused | that call: `invalid_identity` | | `release`, `surface` | A string, 1 to 100 characters | that call: `invalid_field` | | Nesting in `properties`, `traits` | 16 levels | that call: `invalid_field` | | A NUL or half a surrogate pair in any id, key, value, `message_id`, `release` or `surface` | Refused | that call: `invalid_field`, `invalid_identity` or `invalid_message_id` | No rate limit today. `429 rate_limited` with `Retry-After` is reserved; handle it by waiting and resending with the same `message_id`. ### Errors Request-level, as `{ "error": "", "message": "" }`: | Status | `error` | Cause | |---|---|---| | 400 | `invalid_json` | The body is not JSON | | 400 | `invalid_batch` | Not an object or array, empty, or more than 500 calls | | 401 | `missing_credentials` | No `Authorization` header | | 403 | `invalid_credentials` | Unknown slug, wrong secret, or a revoked key | | 403 | `wrong_scope` | A read key sent to a write route, or the reverse | | 403 | `app_archived` | The app is archived and accepts no events (reads still work) | | 413 | `payload_too_large` | The body is over 500 KB | | 429 | `rate_limited` | Reserved, not returned today | | 500 | `write_failed` | Retry with the same `message_id` | Per call, inside `results` with `"status": "rejected"`: `unknown_type`, `missing_event`, `invalid_event_name`, `missing_identity`, `invalid_identity`, `invalid_message_id`, `missing_group`, `event_too_large`, `too_many_properties`, `value_too_long`, `invalid_timestamp`, `invalid_field`, `property_not_allowed`. ### Events from a browser There is no browser key and no CORS: `OPTIONS /api/v1/batch` answers `204` with `Allow: OPTIONS, POST` and no `Access-Control-Allow-*` header, so a browser fails the preflight and never sends the `POST`. **The browser posts to a route on the app's own server, and that route calls Behave.** `@baobabtech/behave/next` builds the route: the user comes from the app's session and never from the posted body, only listed events pass, only listed properties of the listed type pass, a group is attached only when the user belongs to it, `surface` is set by the server, and each user is rate limited. `user.signed_up` and `user.signed_in` are sent from the server where they happen, never relayed. ```ts // app/api/usage/route.ts in a Next.js app: the relay. import { createUsageRoute } from "@baobabtech/behave/next"; import { getCurrentUser, isMember } from "@/lib/auth"; // the app's own session export const POST = createUsageRoute({ allowedEvents: ["page.viewed", "search.performed"], getUser: () => getCurrentUser(), resolveGroup: (user, workspaceId) => isMember(user.id, workspaceId), properties: { "search.performed": { results: "number", area: "string" }, "page.viewed": { page: "string" } }, }); ``` ```ts // in a client component import { createUsageClient } from "@baobabtech/behave/client"; const { reportUsage } = createUsageClient<"page.viewed" | "search.performed">(); reportUsage("search.performed", { results: 24, area: "library" }, workspaceId); ``` Without the package, write the same route by hand: read the user from the session, refuse any event not on a list, keep only listed properties, and send in `after()` with a new `message_id`; never take `message_id` or `user_id` from the browser. ### Forgetting a person When a person deletes their account, `POST /api/v1/forget` with the app's key and `{ "user_id": "u_123", "drop_properties": ["org"] }`. Their events are kept and still counted, but get one new random `user_id` (`forgotten:`) and no `anonymous_id`; the listed property names (up to 20) are removed from them, and their stored traits are deleted. Answers `200` with `{ "forgotten": true, "events": 42, "users": 1 }`; a repeat answers `forgotten: false`. A write key. Forgetting is the app's job, never done on Behave's dashboard: stop sending events for that id, delete the account in the app, then call forget. An event sent just before can still land after it, so a second call a few minutes later catches it; a repeat is safe. Events sent before sign-in with only an `anonymous_id` are not touched. Ingest refuses a `user_id` that starts with `forgotten:`. ## Copy-paste examples One call with curl: ```bash curl -X POST https://behave.baobabtech.app/api/v1/batch \ -H "Authorization: Bearer $BEHAVE_KEY" \ -H "Content-Type: application/json" \ -d '{"type":"track","message_id":"signed_in:sess_5d1e9a20","event":"user.signed_in","user_id":"u_8381","surface":"web"}' ``` A batch, with every field: ```json [ { "type": "track", "message_id": "search_9f21a4", "event": "search.performed", "user_id": "u_8381", "anonymous_id": "a_7f30c1", "timestamp": "2026-10-16T09:13:22.881Z", "group_type": "workspace", "group_id": "ws_412", "release": "2026.10.1", "surface": "web", "properties": { "results": 24, "page": 1, "mode": "filtered" } }, { "type": "identify", "message_id": "u_8381:identify:2026-10-16", "user_id": "u_8381", "traits": { "role": "analyst", "plan": "team" } }, { "type": "group", "message_id": "ws_412:group:2026-10-16", "group_type": "workspace", "group_id": "ws_412", "traits": { "name": "Kenya team" } } ] ``` With fetch, on the server. Analytics must never break the app, so this never throws: ```ts // lib/behave.ts. Server only: BEHAVE_KEY=: const BEHAVE_URL = process.env.BEHAVE_ORIGIN ?? "https://behave.baobabtech.app"; export async function sendToBehave(calls: Record[]): Promise { try { const res = await fetch(`${BEHAVE_URL}/api/v1/batch`, { method: "POST", headers: { Authorization: `Bearer ${process.env.BEHAVE_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify(calls), }); const body = await res.json(); if (!res.ok) return console.warn(`[behave] ${body.error}: ${body.message}`); for (const r of body.results) { if (r.status === "rejected") console.warn(`[behave] ${r.error}: ${r.message}`); } } catch (err) { console.warn("[behave] send failed", err); } } // In a Next.js route, send after the response: // after(() => sendToBehave([{ type: "track", message_id: `signed_up:${user.id}`, event: "user.signed_up", user_id: user.id }])); ``` ## Check the integration Two reads an agent can run after wiring an app, before anyone opens the dashboard. - `GET https://behave.baobabtech.app/api/v1/me`, any key: which app and key this is. Never the secret, an event or a user. ```json { "app": { "slug": "my-app", "name": "My App" }, "key": { "id": "6f1c2e0a-3b7d-4c5e-9a10-2b3c4d5e6f70", "scope": "write", "created_at": "2026-10-21T09:00:00.000Z", "last_used_at": null }, "origin": "https://behave.baobabtech.app", "sdk_min_version": "0.1.0", "server_time": "2026-10-21T09:30:00.000Z" } ``` - `GET https://behave.baobabtech.app/api/v1/reports/ingest-health?window=24h`, a read key: how ingest treated the app's calls. `window` is `h` or `d`, at most 30 days, counted by the hour. `unregistered_events` is the top 50 names sent but not in the registry, usually typos. `failed` counts accepted calls Behave could not store after the `202`, part of `accepted`; above zero is Behave's fault, and resending with the same `message_id` is safe. Counts start at `counted_since`. ```json { "app": "my-app", "window": "24h", "from": "2026-10-20T10:00:00.000Z", "to": "2026-10-21T09:30:00.000Z", "counted_since": "2026-10-21T08:00:00.000Z", "accepted": { "total": 41, "by_type": { "track": 38, "identify": 3 } }, "rejected": { "total": 2, "by_code": { "invalid_event_name": 2 } }, "failed": { "total": 0, "by_type": {} }, "clamped_timestamps": 0, "dropped_properties": 1, "unregistered_events": [ { "name": "serch.performed", "count": 2 } ], "last_seen": [ { "name": "search.performed", "last_at": "2026-10-21T09:29:58.000Z", "registered": true } ] } ``` ## Read numbers back Server side, with a read key. Every response is `Cache-Control: no-store`. - `GET https://behave.baobabtech.app/api/v1/metrics`: the app's metric definitions, `{ "app": "", "metrics": [ { "slug", "label", "template", "unit", "params", "target", "reference", "tile", ... } ] }`. Metrics are defined by the app's admins on the dashboard's Metrics page, not over the API. - `GET https://behave.baobabtech.app/api/v1/metrics/?from=&to=&interval=&by=`: one metric computed, in one shape for every template. `404 unknown_metric` when the app has no such metric. - `GET https://behave.baobabtech.app/api/v1/reports/?from=&to=`: the named reports: `events_over_time`, `top_events`, `active_users`, `activation`, `funnel`, `retention`, `group_breakdown`, `export`. - `GET https://behave.baobabtech.app/api/v1/reports/flows?start=&hops=4`: what people did after an event (or, with `mode=to&end=`, before one), as Sankey columns: `{ started, columns: [ { index, nodes: [ { id, kind, event, people, share, median_to_next_seconds } ] } ], links: [ { source, target, people } ], paths: [ { events, people, share } ] }`. One path per person from their first `start` (or last `end`), stopped at a 30-minute gap (`gap`) or `journey=window&within=7 days`; `hide` repeats, `merge=0` keeps repeats, `where=key=value` and `trait=key=value` filter people, `by` splits. At most 90 days. `from` is inclusive and `to` exclusive, as a date or ISO 8601, UTC. Default: the last 30 days. At most 366 days (`400 range_too_wide`). Other errors: `400 unknown_report`, `400 invalid_parameter`, and the auth codes above. ## The SDK `npm i @baobabtech/behave`: public on npm, MIT, no runtime dependency, no queue. Three entry points: - `@baobabtech/behave`: the server client. `track`, `identify` and `group` each make one `fetch` to `/api/v1/batch` and never throw (failures go to `onError`, default one `console.warn`); `report`, `metrics`, `metric`, `ingestHealth`, `me` and `forget` do throw. - `@baobabtech/behave/next`: `trackFor(user, event, properties?, options?)`, which sends in `after()` and never throws, and `createUsageRoute`, the relay above. Its client takes the release from `BEHAVE_RELEASE`, else the first 7 characters of `VERCEL_GIT_COMMIT_SHA`, and is quiet when no key is set, except in production (`VERCEL_ENV=production`, or `NODE_ENV=production` off Vercel), where it warns once per process. - `@baobabtech/behave/client`: `createUsageClient`, for the browser, which posts to the relay. It reads `BEHAVE_KEY` (write), `BEHAVE_READ_KEY` (read, else `BEHAVE_KEY`), `BEHAVE_RELEASE` (stamped on every `track` as `release`) and the origin from `BEHAVE_ORIGIN` or `NEXT_PUBLIC_BEHAVE_URL`, default `https://behave.baobabtech.app`. Arguments are camelCase (`userId`, `groupType`, `messageId`); the client maps them to the API's snake_case. Without a JavaScript server, use the `fetch` example above, which is the whole contract. ## Links - [Full reference](https://behave.baobabtech.app/llms-full.txt): adds the metric response, every template and report, and the SDK in full. - [Integrating an app](https://behave.baobabtech.app/llms-integrate.txt): the steps, in order, for an agent wiring up an app. - [Ingest route](https://behave.baobabtech.app/api/v1/batch): `POST` only, write key required. - [Key check](https://behave.baobabtech.app/api/v1/me): `GET`, any key. - [Metric definitions](https://behave.baobabtech.app/api/v1/metrics): `GET`, read key required. - [Widget registry item](https://behave.baobabtech.app/r/behave-metric-tile.json): shadcn source, no key. - [Dashboard](https://behave.baobabtech.app/login): sign-in by email code, for the people who run an app. Keys are issued here.