Skip to content
Shortcut: /, ⌘K or Ctrl+K

Installation and setup

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

View as Markdown

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.

  1. Install the packages

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

    Shell
    npm install @polymorfa/react@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.

  2. 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:

    TypeScript
    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.

  3. Add the provider

    TSX
    "use client";
    import { Inbox, PolymorfaProvider } from "@polymorfa/react";
    
    export function Support() {
      return (
        <PolymorfaProvider tokenEndpoint="/api/polymorfa/token">
          <Inbox />
        </PolymorfaProvider>
      );
    }

Server route reference #

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

  • polymorfaMessagingClientrequired

    Server client from @polymorfa/sdk, created with your API key.

  • authenticate(request) => User | nullrequired

    Returns the signed-in user, or null to answer 401. The user needs an id.

  • mint(user, request) => grant | nullrequired

    Returns the user's grant, or null to answer 403. Called on every request.

  • basePathstring

    Path the handler is mounted at.

    Default /api/polymorfa

  • webhooks{ secret, constructEvent, onEvent, signatureHeader? }

    Verifies webhook signatures on the raw body before onEvent runs.

  • history{ conversations, messages, contact? }

    Reads conversations, messages and contact details from your own store.

  • events(context) => AsyncIterable<event>

    Live events as server-sent events. Events outside the grant are dropped.

  • media{ mode, authorize }

    Serves message media to signed-in users.

  • connect(context) => QuickLink input

    The QuickLink to create when the user selects Connect WhatsApp.

  • templates{ projectSlug, submissionSession }

    Resolves the project and submission session for the template editor.

  • heartbeatMsnumber

    Server-sent events heartbeat interval.

    Default 25000

  • onError(error, route) => void

    Receives unexpected errors. Responses never include their details.

Grant fields#

  • sessionstring

    Number session the token acts for.

  • customerstring

    Polymorfa Customer ID for a Customer-scoped token (beta).

  • conversations"all" | string[]required

    Conversation IDs the user may read.

  • allowPolymorfaPermission[]required

    Permissions for this user. At least one.

  • ttlSecondsnumber

    Token lifetime, from 60 to 86400 seconds.

    Default 600

  • ephemeralIdstring

    Stable per-user ID used for rate limits.

    Default The user's id

Routes and permissions#

RouteMethodNeedsPurpose
tokenPOSTSigned-in userMints a client token and returns it with the grant.
webhooksPOSTValid signatureVerifies the raw body, then calls onEvent.
media/:idGETread_messagesServes message media through media.authorize.
history/conversationsGETread_messagesYour conversation list, filtered to the grant.
history/conversations/:id/messagesGETread_messagesMessages for one conversation; 404 outside the grant.
history/conversations/:id/contactGETread_contactContact panel data.
eventsGETsubscribe_eventsServer-sent events, filtered to the grant's session and conversations.
connectPOSTconnect_whatsappCreates a QuickLink; the browser receives only the hosted URL.
templatesPOSTmanage_templatesLists, 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. 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.

Express and Hono#

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

TypeScript
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 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.

  • tokenEndpointstring

    Your token route.

    Default /api/polymorfa/token

  • clientPolymorfaClient

    A client you created. Takes precedence over tokenEndpoint.

  • appearanceAppearanceInput

    Default appearance for every element.

  • localeLocale

    Default interface text.

    Default English

  • registryCustomElementRegistry

    Registry to define the elements in.

    Default customElements

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.

  • tokenEndpointstring

    Same-origin path of your token route. The other routes live next to it.

    Default /api/polymorfa/token

  • baseUrlstring

    API origin for direct client-token requests.

    Default https://api.polymorfa.com

  • refreshBeforeMsnumber

    Refresh this long before expiry.

    Default 60000

  • maxBackoffMsnumber

    Longest wait between failed attempts.

    Default 30000

Permissions in the browser#

Hook or methodReturns
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.