# Integrating an app The steps to connect an app to Behave, in order, for the developer or coding agent doing it. Served as `https://behave.baobabtech.app/llms-integrate.txt`. The HTTP contract is `https://behave.baobabtech.app/llms.txt`; the specs are in `docs/` of the Behave repository. The examples are Next.js (App Router). Any other server calls the same routes with `fetch` (`/llms.txt` has the code). ## 1. Create the app and a key (a person does this) An agent cannot. A super admin of Behave creates the app at `https://behave.baobabtech.app/settings` and picks its slug, which is fixed. An admin of the app then issues keys on the app's Settings page, Keys tab: - a **write** key, for the app's server: it sends events and forgets people; - a **read** key, only if the app reads its numbers back (widgets, scripts). Each secret is shown once. The person puts them in the app's server environment: ```bash BEHAVE_KEY=: BEHAVE_READ_KEY=: # only if the app reads ``` Never in a `NEXT_PUBLIC_*` variable, a browser bundle or a mobile app. An agent without a key asks the person it works for; it never invents one. `BEHAVE_RELEASE` is optional: the app version stamped on every event. On Vercel the Next.js helper falls back to the first 7 characters of `VERCEL_GIT_COMMIT_SHA`. ### One Behave app per environment Test traffic must not move a production number, so an app that deploys previews or a staging site gets two Behave apps, each with its own write key: | Where the app runs | `BEHAVE_KEY` | |---|---| | Production | The production app's key: `:...` | | Preview and staging deployments | The staging app's key: `-staging:...` | | Local development | Unset. Nothing is sent, and the Next.js client says nothing | On Vercel, set `BEHAVE_KEY` once per environment: Production, Preview, and any custom environment such as `staging`. Ask the super admin for both apps at once. With no staging app, leave `BEHAVE_KEY` unset in Preview; never point a preview at the production app. With the key unset in production, nothing is sent; the Next.js client warns once per process (`[behave] no_key`) when `VERCEL_ENV` is `production`, or `NODE_ENV` is off Vercel. ## 2. Install ```bash npm i @baobabtech/behave ``` Public on npm, MIT, no runtime dependency. Three entry points: `@baobabtech/behave` (the server client), `@baobabtech/behave/next` (Next.js helpers, needs `next` 15.1 or later) and `@baobabtech/behave/client` (the browser). ## 3. Check the key ```ts import { behave } from "@baobabtech/behave"; console.log(await behave.me()); ``` It answers the app's slug and name, the key's scope (`write`, `read`, or `all` for a key issued before scopes) and the server's time. It throws with Behave's message when the key is wrong: `invalid_credentials` is a wrong or revoked key, a missing key throws before any request. Run it once from a script or a route; it is not something to call on every request. ## 4. Send events from the server Server events are the reliable ones: the session, the ids and the outcome are all there. ```ts import { trackFor } from "@baobabtech/behave/next"; // in a route handler, server action or server component trackFor(session.user, "export.downloaded", { format: "csv", rows: 120 }, { messageId: `export:${exportId}`, groupType: "workspace", groupId: workspace.id, }); ``` - `trackFor(user, event, properties?, options?)` sends after the response, in `after()`. It never throws, never waits and returns nothing. `user` is the app's user object or its id; with no user it sends nothing. - **Pass `messageId` on any event with a durable id**: the export, the message, the run. Behave stores one row per `messageId`, so a retried request or a double click is counted once. Without one, every call is a new event. - Use the six standard names where they fit: `user.signed_up`, `user.signed_in`, `page.viewed`, `search.performed`, `feature.used`, `feedback.submitted`. Name anything else the same way: a noun, a dot, a past-tense verb, lowercase (`report.exported`). - An app with an MCP server or a public API sends from those route handlers the same way, with `surface` set so the channels can be told apart; the relay in step 5 sets `web`: ```ts // app/api/mcp/route.ts, inside a tool handler trackFor(user, "search.performed", { results: hits.length }, { surface: "mcp" }); ``` ### The auth events `user.signed_up` and `user.signed_in` are sent where the account and the session are created, never from a browser. Auth hooks are where a retry or a double fire happens, so both always carry a `messageId` from the record they are about: | Event | `messageId` | |---|---| | `user.signed_up` | `` `signed_up:${user.id}` `` | | `user.signed_in` | `` `signed_in:${session.id}` `` | Where to hook them: - **Better Auth**: `databaseHooks.user.create.after` and `databaseHooks.session.create.after` in the `betterAuth({ ... })` config. Better Auth runs them after the write commits, inside the auth route's request, so `trackFor`'s `after()` sends once the response is out. ```ts import { trackFor } from "@baobabtech/behave/next"; export const auth = betterAuth({ // ... databaseHooks: { user: { create: { after: async (user) => { trackFor(user, "user.signed_up", undefined, { messageId: `signed_up:${user.id}` }); }, }, }, session: { create: { after: async (session) => { trackFor(session.userId, "user.signed_in", undefined, { messageId: `signed_in:${session.id}` }); }, }, }, }, }); ``` A sign-up that signs the person in creates a session too, so it sends both events, which is right: the account was created and a session began. - **Auth.js (NextAuth)**: `events.createUser` for `user.signed_up`, `events.signIn` for `user.signed_in`. With database sessions use the session id; with JWT sessions there is none, so use `` `signed_in:${user.id}:` ``. - **Clerk**: the `user.created` and `session.created` webhooks, in a route handler. Use the user id and the session id from the payload. - **Anything else**: the line after the account row or the session row is written, on the server. ## 5. Relay browser events A browser never holds a key. It posts to a route on the app's own server, which sends to Behave. ```ts // app/api/usage/route.ts import { createUsageRoute } from "@baobabtech/behave/next"; import { getSession, isMember } from "@/lib/auth"; // the app's own export const POST = createUsageRoute({ allowedEvents: ["page.viewed", "search.performed", "citation.opened"], getUser: async () => (await getSession())?.user, resolveGroup: (user, workspaceId) => isMember(user.id, workspaceId), properties: { "page.viewed": { page: "string" }, "search.performed": { results: "number", area: "string" }, "citation.opened": { area: "string", position: "number" }, }, stripKeys: ["org"], serverProperties: (user) => ({ role: user.role }), }); ``` ```ts // lib/usage.ts, imported by client components import { createUsageClient } from "@baobabtech/behave/client"; export type UsageEvent = "page.viewed" | "search.performed" | "citation.opened"; export const { reportUsage } = createUsageClient(); // reportUsage("search.performed", { results: 24, area: "library" }, workspaceId); ``` What the route does, so the app does not have to: | Rule | Why | |---|---| | The user comes from `getUser`, never from the body | A browser that can name its user can name anyone's. No user answers `401` | | An event not in `allowedEvents` answers `400` | A signed-in user cannot send `user.signed_up` or any name the app did not list | | `properties` lists each event's keys and types; anything else is dropped, strings are cut to 200 characters | No free text reaches Behave from a browser. An allowed event with no entry keeps no properties | | `surface` and `stripKeys` are removed from what the browser sent, then `serverProperties` adds the app's own | Facts about the user, such as an organisation, come from the server | | A `groupId` is attached only when `resolveGroup` returns true, as `groupType` (default `workspace`) | A user cannot put events in a workspace they are not in. Without `resolveGroup`, every group is dropped | | 60 events a minute per user, then `429` with `Retry-After` | Stops a loop in one tab. Per server instance; pass `rateLimit` for a shared limit | | `messageId` and `timestamp` from the browser are ignored | A browser that picks message ids could block a server event by sending its id first | | Answers `202` at once and sends in `after()` | The page never waits on Behave | `reportUsage` posts with `keepalive`, so it survives a navigation, and swallows every failure. Its type parameter makes a misspelled event a type error; the route's `allowedEvents` is still the gate. ## 6. Rules - **Signed-in use only.** Send events for signed-in people. A page an anonymous visitor sees is outside what Behave counts, unless the app has a reason and sends an `anonymousId`. - **No free text and no personal data in properties.** Never a query, a prompt, a message, a title, a file name, a name or an email. A count, an id, a boolean or a short fixed category is fine; the text that produced the category is not. Behave enforces it when the app's admins set a property list on each event (step 8). - **Traits are categories, never PII.** `identify` and `group` traits follow the property rule: a role, a plan, an organisation, an email domain or a locale is fine; a person's name, email or phone number is not. A group's `name` is the group's, such as the workspace's. - **`area`, not `surface`, for where in the app.** `surface` is the channel (`web`, `api`, `mcp`) and the relay sets it. Where on the page or in the app is a property: `area: "chat"`. - **The user id comes from the session, never from a request body**, on the server as in the relay. Use the app's stable database id, never an email. ## 7. When someone deletes their account ```ts import { behave } from "@baobabtech/behave"; await behave.forget({ userId: user.id, dropProperties: ["org", "email_domain"] }); ``` `forget` replaces the person's user id on every event with one random `forgotten:`, removes the listed property names from those events, and deletes their stored traits. Their events stay counted, so past numbers do not move. It needs a write key, and it throws on failure, because the caller is deleting an account and needs to know. In this order: 1. Stop sending events for the person: sign them out and end their sessions. 2. Delete the account in the app. 3. Call `forget`, with every property name that could point back at them. 4. Call it again a few minutes later. An event sent just before the deletion can arrive after the first call; a repeat is safe and answers `forgotten: false` when there was nothing left. ## 8. Check what arrived, then register the names ```ts console.log(await behave.ingestHealth("24h")); ``` It needs a read key (or a key issued before scopes) and answers, for the window: - `accepted` by call type and `rejected` by code: a rejected call was never stored; - `failed` by call type: accepted calls Behave could not store after answering `202`. Above zero is Behave's fault, not the app's; resending with the same `messageId` is safe; - `clamped_timestamps`: events stored at arrival time because their timestamp was more than 7 days old or more than 5 minutes ahead; - `dropped_properties`: calls that lost a property their event's list does not have; - `unregistered_events`: names sent but not in the app's registry, top 50, usually typos; - `last_seen`: each name's latest event in the window. Then ask an admin of the app to register every name on the Settings page, Events tab, with a sentence each and, for each event, its properties with a type each. With a list set, ingest drops any other property; with the app set to refuse, it rejects the call as `property_not_allowed`. The six standard events come with their properties defined by Behave; the app adds its own beside them, and may send properties it never listed on a standard event. ## 9. Pitfalls - **`after()` outside a request scope throws.** `trackFor` catches it and sends at once, so a script still sends; keep the script alive until the promise settles. A hand-written `after(() => behave.track(...))` at module level or in a script throws. - **React strict mode runs effects twice in development.** An event fired from `useEffect` is sent twice. Guard it with a ref: ```ts const sent = useRef(false); useEffect(() => { if (sent.current) return; sent.current = true; reportUsage("page.viewed", { page: "/library" }); }, []); ``` - **Arriving on a page is not an action.** `page.viewed` is the page load; a search, an export or a click is its own event, fired where it happens, not inferred from the page it lands on. - **`useEffect` fires again on back and forward navigation** and on a client-side remount. Fire the event from the handler of the act, not from an effect, whenever there is a handler. - **Awaited or fire-and-forget.** `behave.track` returns a promise that never rejects; awaiting it puts a round trip on the request. In Next.js use `trackFor`, which never waits. Await only `forget`, `me`, `ingestHealth` and the reads, which throw.