# Installation and setup

> Install the UI Kit, add the server token route and wrap your interface in the provider.

Setup has two halves: a server route that mints client tokens for your
signed-in users, and a provider in the browser that fetches and refreshes them.

### Install the packages

Install the prerelease from the `dev` tag and pin the exact version in your
`package.json`.

**React**

```bash
npm install @polymorfa/react@dev @polymorfa/browser@dev
npm install @polymorfa/nextjs@dev @polymorfa/sdk@dev
```

**Web Components**

```bash
npm install @polymorfa/elements@dev @polymorfa/browser@dev
npm install @polymorfa/nextjs@dev @polymorfa/sdk@dev
```

The second line installs the server packages. Install them where your server
code runs.

### Add the server route

`createPolymorfaHandler` serves every route the components call from one
catch-all route. In a Next.js App Router project, create
`app/api/polymorfa/[...route]/route.ts`:

```ts
import { MessagingClient, constructWebhookEvent } from "@polymorfa/sdk";
import { createPolymorfaHandler } from "@polymorfa/nextjs";

export const { GET, POST } = createPolymorfaHandler({
  polymorfa: new MessagingClient({
    credential: { type: "apiKey", value: process.env.POLYMORFA_API_KEY! },
  }),
  authenticate: (request) => currentUser(request), // your auth; null answers 401
  mint: (user) => ({
    session: "support",
    conversations: user.assignedConversationIds, // or "all"
    allow: ["read_messages", "subscribe_events", "send_message"],
    ttlSeconds: 600,
  }),
  history: { conversations: listConversations, messages: listMessages },
  events: streamEvents,
});
```

`mint` is the only place permissions are chosen. Return `null` to refuse the
user (`403`). `allow` must list at least one permission and `conversations`
must be explicit; there is no default that grants everything. The handler calls
`authenticate` and `mint` on every request, so revoked access takes effect on
the next call. The browser never sends permissions.

### Add the provider

**React**

```tsx
"use client";
import { Inbox, PolymorfaProvider } from "@polymorfa/react";

export function Support() {
  return (
    <PolymorfaProvider tokenEndpoint="/api/polymorfa/token">
      <Inbox />
    </PolymorfaProvider>
  );
}
```

**Web Components**

```ts
import { definePolymorfa } from "@polymorfa/elements";

definePolymorfa({ tokenEndpoint: "/api/polymorfa/token" });
```

```html
<pmfa-session-status></pmfa-session-status>
<pmfa-inbox style="height: 640px"></pmfa-inbox>
```

## Server route reference

`createPolymorfaHandler(options)` returns `{ GET, POST, handle }`. Mount it at
`/api/polymorfa` or set `basePath`.

| Option | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `polymorfa` | `MessagingClient` | Yes | | Server client from `@polymorfa/sdk`, created with your API key. |
| `authenticate` | `(request) => User \| null` | Yes | | Returns the signed-in user, or `null` to answer `401`. The user needs an `id`. |
| `mint` | `(user, request) => grant \| null` | Yes | | Returns the user's grant, or `null` to answer `403`. Called on every request. |
| `basePath` | `string` | No | `/api/polymorfa` | Path the handler is mounted at. |
| `webhooks` | `{ secret, constructEvent, onEvent, signatureHeader? }` | No | | Verifies webhook signatures on the raw body before `onEvent` runs. |
| `history` | `{ conversations, messages, contact? }` | No | | Reads conversations, messages and contact details from your own store. |
| `events` | `(context) => AsyncIterable<event>` | No | | Live events as server-sent events. Events outside the grant are dropped. |
| `media` | `{ mode, authorize }` | No | | Serves message media to signed-in users. |
| `connect` | `(context) => QuickLink input` | No | | The QuickLink to create when the user selects Connect WhatsApp. |
| `templates` | `{ projectSlug, submissionSession }` | No | | Resolves the project and submission session for the template editor. |
| `heartbeatMs` | `number` | No | `25000` | Server-sent events heartbeat interval. |
| `onError` | `(error, route) => void` | No | | Receives unexpected errors. Responses never include their details. |

### Grant fields

| Field | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `session` | `string` | One of `session` or `customer` | | Number session the token acts for. |
| `customer` | `string` | One of `session` or `customer` | | Polymorfa Customer ID for a [Customer-scoped token](https://docs.polymorfa.com/development/client-tokens#customer-scoped-tokens) (beta). |
| `conversations` | `"all" \| string[]` | Yes | | Conversation IDs the user may read. |
| `allow` | `PolymorfaPermission[]` | Yes | | Permissions for this user. At least one. |
| `ttlSeconds` | `number` | No | `600` | Token lifetime, from 60 to 86400 seconds. |
| `ephemeralId` | `string` | No | The user's `id` | Stable per-user ID used for rate limits. |

### Routes and permissions

| Route | Method | Needs | Purpose |
| --- | --- | --- | --- |
| `token` | POST | Signed-in user | Mints a client token and returns it with the grant. |
| `webhooks` | POST | Valid signature | Verifies the raw body, then calls `onEvent`. |
| `media/:id` | GET | `read_messages` | Serves message media through `media.authorize`. |
| `history/conversations` | GET | `read_messages` | Your conversation list, filtered to the grant. |
| `history/conversations/:id/messages` | GET | `read_messages` | Messages for one conversation; `404` outside the grant. |
| `history/conversations/:id/contact` | GET | `read_contact` | Contact panel data. |
| `events` | GET | `subscribe_events` | Server-sent events, filtered to the grant's session and conversations. |
| `connect` | POST | `connect_whatsapp` | Creates a QuickLink; the browser receives only the hosted URL. |
| `templates` | POST | `manage_templates` | Lists, saves, previews and submits templates. |

Your route enforces `read_messages`, `subscribe_events`, `connect_whatsapp`,
`manage_templates` and `conversations`. Polymorfa enforces the actions on the
client token itself (`send_message`, `send_reaction`, `send_typing`,
`send_seen`, `read_presence`, `subscribe_presence`, `read_contact` and the
`voip_*` actions) from the session's [client rules](https://docs.polymorfa.com/development/client-tokens#session-rules).
For a Customer grant, the route forwards the API actions in `allow` and refuses
a grant that has none.

The key that mints tokens needs `sessions:manage`, `messages:write`,
`contacts:read`, `presence:read`, `presence:observe` and `mcp`. A Customer
grant also needs `customers:read`. See [Client tokens](https://docs.polymorfa.com/development/client-tokens#mint).

### Express and Hono

The handler uses the Fetch `Request` and `Response` APIs. Other servers use an
adapter:

```ts
import { toExpress } from "@polymorfa/nextjs/express";
app.use("/api/polymorfa", toExpress(handler)); // before express.json()

import { toHono } from "@polymorfa/nextjs/hono";
app.all("/api/polymorfa/*", toHono(handler));
```

Mount `toExpress` before `express.json()`. Webhook signatures are checked
against the raw body.

### Development inbox store

`createDevelopmentInboxStore()` keeps webhook events in memory and serves them
as `history` and `events`, so `<Inbox/>` shows messages before you build
storage. The data is lost on restart and is not shared between server
instances. Replace it with your database before production.

## Provider reference

### PolymorfaProvider

All 5 `PolymorfaProvider` props, with types, defaults and a live preview, are on the [PolymorfaProvider](https://docs.polymorfa.com/ui-kit/components/polymorfa-provider) page.

Without `tokenEndpoint` or `client`, the provider supplies only appearance and
locale. Components that need the shared client, such as `<Inbox/>`, require
one of them. Chat and call components that receive a controller work without
either.

### definePolymorfa

`definePolymorfa(options)` is the Web Components equivalent. It creates one
client, starts fetching a token, registers every element and returns the
client. `<pmfa-inbox>`, `<pmfa-connect-whatsapp>` and `<pmfa-session-status>`
use that client unless you set their `client` property.

| Option | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `tokenEndpoint` | `string` | No | `/api/polymorfa/token` | Your token route. |
| `client` | `PolymorfaClient` | No | | A client you created. Takes precedence over `tokenEndpoint`. |
| `appearance` | `AppearanceInput` | No | | Default appearance for every element. |
| `locale` | `Locale` | No | English | Default interface text. |
| `registry` | `CustomElementRegistry` | No | `customElements` | Registry to define the elements in. |

To register the elements without creating a client, call
`definePolymorfaElements()`. It defines `pmfa-message-list`,
`pmfa-compose-box`, `pmfa-chat-window`, `pmfa-chat-drawer`,
`pmfa-template-builder`, `pmfa-call`, `pmfa-inbox`, `pmfa-connect-whatsapp`
and `pmfa-session-status`. Elements that are already defined are left in place.

## Token refresh and failures

The client posts to your token route, caches the token and refreshes it 60
seconds before expiry (at 80% of the lifetime for short tokens). Failed
attempts retry with exponential backoff and jitter, from 1 second up to 30
seconds. A `401` or `403` stops retries until you call `refresh()`.

The client reports its state as `idle`, `loading`, `ready`, `refreshing`,
`retrying`, `unauthenticated` or `error`. `<SessionStatus/>` and
`<pmfa-session-status>` show it as a badge.

Your route's responses are checked for status and content type. An HTML error
page from a proxy becomes a clear error rather than a parse failure.

### PolymorfaClient options

Create a client yourself with `createPolymorfaClient(options)` from
`@polymorfa/browser` when you need to share it outside React or change the
defaults.

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `tokenEndpoint` | `string` | `/api/polymorfa/token` | Same-origin path of your token route. The other routes live next to it. |
| `baseUrl` | `string` | `https://api.polymorfa.com` | API origin for direct client-token requests. |
| `refreshBeforeMs` | `number` | `60000` | Refresh this long before expiry. |
| `maxBackoffMs` | `number` | `30000` | Longest wait between failed attempts. |

## Permissions in the browser

| Hook or method | Returns |
| --- | --- |
| `usePolymorfaClient()` | The provider's client. Throws outside a provider with `tokenEndpoint` or `client`. |
| `useOptionalPolymorfaClient()` | The provider's client, or `undefined`. |
| `usePermissions()` | `{ status, snapshot, can(permission) }`. `can()` returns `true` without a provider client, so controls render and the server decides. |
| `client.can(permission)` | Whether the current grant allows the permission. `false` until a token is minted. |
| `client.canRead(conversationId)` | Whether the grant covers the conversation. |

These checks decide what to render. They never widen access.

## Use a client token without the handler

The call and chat components also accept controllers you create yourself. For
calls, `createClientTokenProvider()` from `@polymorfa/browser` posts to
`/api/polymorfa/token` (or the `path` you pass) and returns the token. Any route
that mints a client token for the signed-in user works. See
[Calls](https://docs.polymorfa.com/ui-kit/calls#setup).
