# JavaScript SDK

> The onari npm package for Node.js, Bun, Deno and edge runtimes.

Source: https://docs.onari.xyz/docs/sdk

`onari` is a small, typed client for the API with no dependencies. It runs on your **server** (it uses your secret key): Node.js 18+, Bun, Deno, Cloudflare Workers, and Next.js route handlers and server actions.

```bash
npm install onari
```

```ts
import { Onari } from "onari";

const onari = new Onari({ apiKey: process.env.ONARI_SECRET_KEY }); // sk_test_… or sk_live_…
```

## Events

```ts
const result = await onari.events.send({
  type: "order.placed",
  playerId: "user_8a21",
  amount: 1_840_000, // minor units
  properties: { channel: "web" },
  idempotencyKey: "order_SE-88213",
});

result.campaigns; // progress toward each running campaign
result.rewards; // anything the player just won

await onari.events.sendBatch([
  { type: "order.placed", playerId: "user_8a21", idempotencyKey: "order_1" },
  { type: "order.placed", playerId: "user_9b02", idempotencyKey: "order_2" },
]);
```

Field names follow the [Events API](/docs/api/events) in camelCase (`playerId`, `idempotencyKey`, `occurredAt`, `referredBy`).

## Players and the Rewards Hub

```ts
await onari.players.create("user_9b02", { referredBy: "user_8a21" });
const profile = await onari.players.get("user_8a21");

const { url, expiresAt } = await onari.hub.createSession({ playerId: "user_8a21", path: "/me" });
```

## Website embed signatures

```ts
import { signPlayer } from "onari";

const signature = await signPlayer(process.env.ONARI_IDENTITY_SECRET, customer.id);
```

See [Website embed](/docs/website-embed).

## Verify webhooks

```ts
import { verifyWebhook, WebhookVerificationError } from "onari";

export async function POST(req: Request) {
  const body = await req.text(); // the raw body
  try {
    const msg = await verifyWebhook(process.env.ONARI_WEBHOOK_SECRET, body, req.headers);
    if (msg.type === "reward.issued") {
      // msg.id is the same on every retry: pay once per id.
    }
    return new Response(null, { status: 200 });
  } catch (err) {
    if (err instanceof WebhookVerificationError) return new Response("Invalid signature", { status: 400 });
    throw err;
  }
}
```

It checks the [Standard Webhooks](/docs/webhooks) signature and rejects messages more than 5 minutes old (`{ toleranceSeconds }` to change it). With Express, use `express.raw({ type: "application/json" })` and pass `req.body`.

## Errors and retries

API errors throw `OnariError` with `status`, `code` (see [Errors](/docs/api/errors)), `message` and `details`:

```ts
import { OnariError } from "onari";

try {
  await onari.events.send({ type: "order.placd", playerId: "user_8a21" });
} catch (err) {
  if (err instanceof OnariError && err.code === "unknown_event_type") console.log(err.details.did_you_mean); // "order.placed"
}
```

Network errors, `429` and `5xx` are retried twice with backoff (`maxRetries` to change). Events are only retried when they have an `idempotencyKey`, so a retry never counts twice.

| Option | Default |
|---|---|
| `apiKey` | required |
| `baseUrl` | `https://api.onari.xyz` |
| `timeoutMs` | `15000` |
| `maxRetries` | `2` |
| `fetch` | `globalThis.fetch` |
