> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.rydhm.ai/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.rydhm.ai/_mcp/server.

# Set up the coach with code

This page is for developers. The [no-code set-up](/engine/onboarding-coach) and this one can be mixed: a script tag with a few calls, or the npm package with everything in code.

## Install

```bash
npm install @rydhm/web
```

```typescript
import { Rydhm } from "@rydhm/web";

const rydhm = Rydhm.init({
  key: "rydhm_pk_live_…",                       // a publishable key: safe in the page
  user: { id: user.id, hash: user.rydhmHash, name: user.name },
  navigate: (path) => router.push(path),        // your router
});
```

`Rydhm.init` makes one cheap request (the bubble, guides and announcements due for this user) and no voice connection. Voice starts only when the person clicks the bubble, or when you call `await rydhm.start()` from a click. `livekit-client` is loaded with a dynamic `import()`, so visitors who never talk to the coach never download it.

> **Note**
>
> **Early access.** Workspaces on `staging.rydhm.ai` pass `apiUrl: "https://api-staging.rydhm.ai"` to `Rydhm.init`.

## Signed users

By default the user id you pass is stored as anonymous (`anon_<id>`): anyone could claim it, so it can never read a signed user's progress. To prove who the user is, your **server** signs the id with the workspace's user-signing secret, and the page passes the id with its `hash`. Turn on **Only signed-in users** on the website key (the coach's **Settings** → **Website keys**; `requireSignedUser: true` in the API) to refuse everyone else.

The secret belongs to the workspace: an admin creates it in the coach's **Settings** → **Signed-in users** → **Create secret** (or **Rotate secret**). It's shown once, so store it with your server's other secrets as `RYDHM_ENGINE_USER_SECRET`. The hash is `hex(HMAC-SHA256(secret, userId))`, the same scheme as Intercom's identity verification:

#### Node (@rydhm/sdk)

**`app/api/rydhm-user/route.ts`**

```typescript title="app/api/rydhm-user/route.ts"
import { signUserId } from "@rydhm/sdk";

export async function GET() {
  const user = await currentUser(); // your auth
  return Response.json({
    id: user.id,
    name: user.name,
    hash: signUserId(process.env.RYDHM_ENGINE_USER_SECRET!, user.id),
  });
}
```

#### Python (rydhm)

```python
import os
from rydhm import sign_user_id

user_hash = sign_user_id(os.environ["RYDHM_ENGINE_USER_SECRET"], user.id)
```

#### Any language

```typescript
// The secret is used as text (its UTF-8 bytes), not decoded from hex.
import { createHmac } from "node:crypto";
const hash = createHmac("sha256", process.env.RYDHM_ENGINE_USER_SECRET!).update(user.id).digest("hex");
```

Then in the page:

```typescript
const me = await fetch("/api/rydhm-user").then((r) => r.json());
rydhm.identify({ id: me.id, hash: me.hash, name: me.name, traits: { plan: "pro", role: "admin" } });
```

Never compute the hash in the browser, and never send the secret there. `signUserId` refuses ids the Engine would refuse: empty, longer than 200 characters, with spaces around them or control characters, or starting with `anon_`. `traits` (up to 4 KB) are what [audiences](/engine/onboarding-coach#guides) match on.

## Tell the coach what's going on

```typescript
// What the coach should know about this user and screen (≤ 4 KB of JSON), live within 250 ms.
rydhm.setContext({ plan: "pro", seats: 12, projects: 3, trialEndsAt: "2026-12-01" });

// Something happened: for analytics, guide triggers ("event") and step completion.
rydhm.track("invite_sent", { count: 2 });
```

The coach already knows the page's address and title; you don't need to send them. Page addresses are sent without their query string.

## Give it your own tools

A tool is a function in your page that the coach can call: look something up, open a dialog, change a setting. Describe its arguments with JSON Schema:

```typescript
const unregister = rydhm.registerTool(
  "get_invoices",
  {
    description: "Recent invoices of this workspace: number, date, amount, status.",
    parameters: {
      type: "object",
      properties: { limit: { type: "integer", description: "How many, 1–20." } },
    },
  },
  async ({ limit = 5 }, { signal }) => {
    const res = await fetch(`/api/invoices?limit=${limit}`, { signal });
    return res.json(); // any JSON, up to 15 KB
  },
);
```

Names are lowercase with underscores (2 to 41 characters), and a page can register up to 20. The handler's `signal` aborts when the coach stops waiting. Throw an `Error` to tell the coach it failed: its message is what the coach hears. See [Client tools](/engine/client-tools) for the full protocol.

## Navigation with your router

The coach changes page with the built-in `navigate` tool. Give it your router so pages change the way a click would:

#### Next.js (App Router)

**`app/rydhm-coach.tsx`**

```tsx title="app/rydhm-coach.tsx"
"use client";
import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { Rydhm } from "@rydhm/web";

export function RydhmCoach({ user }: { user: { id: string; hash: string; name: string } }) {
  const router = useRouter();
  useEffect(() => {
    const rydhm = Rydhm.init({
      key: process.env.NEXT_PUBLIC_RYDHM_PUBLISHABLE_KEY!,
      user,
      navigate: (path) => router.push(path),
    });
    return () => rydhm.destroy();
  }, [router, user]);
  return null;
}
```

#### React Router

```tsx
import { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Rydhm } from "@rydhm/web";

export function RydhmCoach() {
  const navigate = useNavigate();
  useEffect(() => {
    const rydhm = Rydhm.init({ key: import.meta.env.VITE_RYDHM_PUBLISHABLE_KEY, navigate: (path) => navigate(path) });
    return () => rydhm.destroy();
  }, [navigate]);
  return null;
}
```

#### Script tag

```html
<script>window.Rydhm=window.Rydhm||function(){(window.Rydhm.q=window.Rydhm.q||[]).push(arguments)};</script>
<script>
  // A queued init is merged over the data-* options: the way to pass a function.
  Rydhm('init', { navigate: (path) => { location.hash = '#' + path; } });
</script>
<script src="https://staging.rydhm.ai/engine.js" data-key="rydhm_pk_live_…" async></script>
```

Without a router, `navigate: 'auto'` (the default) uses `history.pushState`, and loads the page for real if nothing on the page changed within 700 ms. The coach can never navigate to another website.

## Your own UI (headless)

With `ui: 'none'` nothing is drawn, and everything still works: the spotlight still highlights, and risky clicks still ask (your `confirm`, or the browser's). Build your own button and captions from the events:

```typescript
const rydhm = Rydhm.init({
  key,
  ui: "none",
  confirm: (req) => myDialog.ask(`${req.label}? (${req.reason})`), // resolve true only on a clear yes
});

talkButton.onclick = () => rydhm.start();
rydhm.on("state", ({ state }) => (orb.dataset.state = state)); // idle, connecting, listening, thinking, speaking
rydhm.on("transcript", (t) => captions.upsert(t.id, t.speaker, t.text, t.final));
rydhm.on("guide", (e) => e.type === "offer" && nudge.show(e.guide.name, e.accept, e.dismiss));
rydhm.on("error", (e) => toast(e.message, e.fix));
```

Every option, method, event and error code is in the [Browser SDK reference](/developers/sdk-web).

## Guides and the page map as code

Keep the page map and your guides in your repository and push them from CI with a secret key (scope `experts:write`), so they change with your UI.

#### TypeScript

**`scripts/rydhm-sync.ts`**

```typescript title="scripts/rydhm-sync.ts"
import { Rydhm } from "@rydhm/sdk";

const rydhm = new Rydhm(); // RYDHM_API_KEY
const expertId = process.env.RYDHM_EXPERT_ID!;

// Creates what is missing, updates what changed (by name); prune deletes the rest.
await rydhm.engine.pageTargets.sync(expertId, [
  { name: "Invite button", selector: "[data-test=invite]", textHint: "Invite", pagePattern: "/settings/team" },
  { name: "Billing tab", textHint: "Billing", pagePattern: "/settings/*" },
], { prune: true });

const guides = await rydhm.engine.guides.list(expertId);
const invite = {
  name: "Invite your team",
  nudge: "Want me to show you how to invite your team?",
  trigger: { type: "page", pattern: "/settings/*" } as const,
  steps: [
    {
      id: "open-team",
      title: "Open Team settings",
      instruction: "Take them to Settings → Team.",
      pagePattern: "/settings/team",
      completeWhen: { type: "page", value: "/settings/team" } as const,
    },
    {
      id: "send-invite",
      title: "Send an invite",
      instruction: "Point at the Invite button and explain they can paste several addresses.",
      target: "Invite button",
      completeWhen: { type: "event", value: "invite_sent" } as const,
    },
  ],
};
const existing = guides.find((g) => g.name === invite.name);
if (existing) await rydhm.engine.guides.update(expertId, existing.id, invite);
else await rydhm.engine.guides.create(expertId, invite);
```

#### Python

**`scripts/rydhm_sync.py`**

```python title="scripts/rydhm_sync.py"
import os
from rydhm import Rydhm

client = Rydhm()  # RYDHM_API_KEY
expert_id = os.environ["RYDHM_EXPERT_ID"]

client.engine.page_targets.sync(expert_id, [
    {"name": "Invite button", "selector": "[data-test=invite]", "textHint": "Invite", "pagePattern": "/settings/team"},
    {"name": "Billing tab", "textHint": "Billing", "pagePattern": "/settings/*"},
], prune=True)

steps = [
    {"id": "open-team", "title": "Open Team settings", "instruction": "Take them to Settings → Team.",
     "pagePattern": "/settings/team", "completeWhen": {"type": "page", "value": "/settings/team"}},
    {"id": "send-invite", "title": "Send an invite", "instruction": "Point at the Invite button.",
     "target": "Invite button", "completeWhen": {"type": "event", "value": "invite_sent"}},
]
existing = next((g for g in client.engine.guides.list(expert_id) if g.name == "Invite your team"), None)
if existing:
    client.engine.guides.update(expert_id, existing.id, steps=steps)
else:
    client.engine.guides.create(expert_id, name="Invite your team",
                                nudge="Want me to show you how to invite your team?",
                                trigger={"type": "page", "pattern": "/settings/*"}, steps=steps)
```

`completeWhen` takes `value`, or the browser SDK's own name for it: `pattern` for a page, `target` for a click, `name` for an event or a tool. Announcements and publishable keys work the same way: `rydhm.engine.announcements.create(expertId, { title, body, guideId })` and `rydhm.engine.publishableKeys.create(expertId, { allowedOrigins })`. See the [TypeScript SDK](/developers/sdk-typescript#onboarding-coach) and the [API reference](/api-reference).

The `examples/onboarding-coach-html` (script tag, plus `create-guide.mjs` that creates a sample guide) and `examples/onboarding-coach-nextjs` (signed users through an API route, a custom tool, the App Router) folders that come with the SDKs run as they are.