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
devtag and pin the exact version in yourpackage.json.Shell npm install @polymorfa/react@dev @polymorfa/browser@dev npm install @polymorfa/nextjs@dev @polymorfa/sdk@devThe second line installs the server packages. Install them where your server code runs.
Add the server route
createPolymorfaHandlerserves every route the components call from one catch-all route. In a Next.js App Router project, createapp/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, });mintis the only place permissions are chosen. Returnnullto refuse the user (403).allowmust list at least one permission andconversationsmust be explicit; there is no default that grants everything. The handler callsauthenticateandminton every request, so revoked access takes effect on the next call. The browser never sends permissions.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.
polymorfaMessagingClientrequiredServer client from
@polymorfa/sdk, created with your API key.authenticate(request) => User | nullrequiredReturns the signed-in user, or
nullto answer401. The user needs anid.mint(user, request) => grant | nullrequiredReturns the user's grant, or
nullto answer403. Called on every request.basePathstringPath the handler is mounted at.
Default
/api/polymorfawebhooks{ secret, constructEvent, onEvent, signatureHeader? }Verifies webhook signatures on the raw body before
onEventruns.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 inputThe QuickLink to create when the user selects Connect WhatsApp.
templates{ projectSlug, submissionSession }Resolves the project and submission session for the template editor.
heartbeatMsnumberServer-sent events heartbeat interval.
Default
25000onError(error, route) => voidReceives unexpected errors. Responses never include their details.
Grant fields#
sessionstringNumber session the token acts for.
customerstringPolymorfa Customer ID for a Customer-scoped token (beta).
conversations"all" | string[]requiredConversation IDs the user may read.
allowPolymorfaPermission[]requiredPermissions for this user. At least one.
ttlSecondsnumberToken lifetime, from 60 to 86400 seconds.
Default
600ephemeralIdstringStable per-user ID used for rate limits.
Default The user's
id
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. 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:
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.
tokenEndpointstringYour token route.
Default
/api/polymorfa/tokenclientPolymorfaClientA client you created. Takes precedence over
tokenEndpoint.appearanceAppearanceInputDefault appearance for every element.
localeLocaleDefault interface text.
Default English
registryCustomElementRegistryRegistry 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.
tokenEndpointstringSame-origin path of your token route. The other routes live next to it.
Default
/api/polymorfa/tokenbaseUrlstringAPI origin for direct client-token requests.
Default
https://api.polymorfa.comrefreshBeforeMsnumberRefresh this long before expiry.
Default
60000maxBackoffMsnumberLongest wait between failed attempts.
Default
30000
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.