Skip to content

Initialise the SDK

Your app makes one Crm, the facade, as it starts, and starts it once in the browser. Then it tells the facade who is signed in, and when they are ready, and draws what the facade holds.

src/crm.ts
import { Crm, CrmAuth, CrmTokens } from "crm-sdk";
// The user's token, signed by your backend: see "Sign users in".
export const tokens = CrmTokens.fetched(async () => {
const answer = await fetch("/crm-token");
return answer.ok ? (await answer.json()).token : null; // null: nobody signed in
});
export const crm = new Crm({
config: {
apiBase: "https://app.purrcrm.com",
appKey: "app_...", // from the App key card on Settings › your app › Developers › Install
appVersion: "2.4.0", // your app's own version
},
auth: CrmAuth.tokens(tokens),
host: {
navigate: (where, how) => showCrmPage(where, how), // see "Host hooks" below
followable: (link) => (link.startsWith("/offers/") ? link : null),
openInApp: (location) => router.push(location),
},
});
src/main.ts
import { crm } from "./crm";
await crm.start();
void crm.handleLink(location.href); // the address the page loaded at, once: see Links
// When your own sign-in has settled:
crm.session({ guestId: user.id });
crm.setReady(true); // past your own first steps: onboarding, a consent screen

crm.start() runs once, however often it is called. It reads back the events a previous load of the page left waiting, records app_opened (and app_updated when the app’s version changed since the last load in this browser), starts reading your app’s public face from PurrCRM, and from then on follows the page being hidden and shown. With debug: true it loads the setup check once the page has loaded.

The app’s public face is its name, accent and logo, which parts are switched on, its currency, languages and link base. The SDK keeps it in the browser, so the next load has it at once, even offline; crm.publicApp holds it, and crm.productName is your productName or else the brand’s name.

crm.session({ guestId: user.id, displayName: user.name }); // signed in
crm.setReady(true);
crm.session(null); // signed out

Call session whenever your own session changes, once it has settled. A different user, or nobody, makes the facade forget the last one’s messages, conversations, notices and queued events, so the next user in the browser sees only theirs. guestId is your own id for the user, the token’s sub (Sign users in).

Until setReady(true) nothing of PurrCRM‘s shows (crm.inApp.next and crm.inApp.banner stay null), and a link or a tapped push waits. Call setReady(false) while the user is somewhere nothing should interrupt, and true again after.

CrmSession also takes productEventsOff: true, for a user who turned product analytics off in your settings (Events), and features, to hold some of PurrCRM‘s parts back from a user (Messenger).

CrmConfig describes your app:

FieldWhat it is
apiBaseYour PurrCRM address, https://app.purrcrm.com. Required.
appKeyYour app’s key (app_…, or app_test_… in a staging build). Required.
appVersionYour app’s own version, sent with every request and every batch of events. Required.
productNameWhat your users call your app. Left out, the name set for your app on PurrCRM is used.
storagePrefixWhat every key the SDK keeps in the browser starts with, followed by a dot: crm unless you name one. Two apps on one site each name their own. Pick it once and keep it, or events waiting are lost.
initialFeaturesThe parts to have in a browser that has never reached PurrCRM ("messenger", "help_center", "in_app_messages"). None unless you name some.
customEventsYour own events, by name: see Events.
followLifecycleWhether the facade follows the page being hidden and shown. On; turn it off only in tests.
languageTagA function answering the user’s language (en-GB), sent as Accept-Language so that PurrCRM answers in it. The browser’s first language unless you set it; set it to follow your app’s own language choice.
flushEveryMsHow often waiting events are sent, in milliseconds (30 000).
storeWhere the SDK keeps what it keeps: localStorage unless you hand in another CrmStore, such as MemoryCrmStore in a test.
fetchThe fetch to use: the browser’s unless you hand in another, such as a fake in a test.
nowThe clock: the browser’s unless a test hands in its own.
debugTurns on the setup check and writes every request to the logger. Never in what your users get.
releaseBuildWhether this is the build your users get. The SDK cannot tell a production bundle by itself; set it from your bundler (import.meta.env.PROD, process.env.NODE_ENV === "production") so that a test key or debug in it is warned about (Test mode).
loggerWhere the SDK writes what it has to say: the browser’s console unless you hand in a CrmLogger (debug and warn).

CrmHost is what your app does for the SDK. Every hook is optional; leaving one out means the SDK does without it. Hand them in with the facade, or later, once they exist: crm.host = { ...crm.host, navigate }.

HookWhat it doesWithout it
navigate(where, how)Shows one of PurrCRM‘s pages in your app: where is a CrmDestination, how is "open" (in place of the page the user is on: a tapped push, a link) or "push" (over it, so Back comes back: a tap inside PurrCRM‘s pages). Answers whether it could.PurrCRM‘s pages and tapped pushes go nowhere.
followable(link)Your allow-list: where a link in a message (/offers/123) goes in your app, or null for nowhere.Links into your app go nowhere.
openInApp(location)Goes to a place followable allowed: your router.The same.
openExternal(url)Opens an https page outside your app.A new tab, with noopener.
timeZone()The user’s IANA time zone.The browser’s, from Intl.
askPermission(permission)Asks the browser for a permission a carousel’s button asks for ("notifications", "location"), answering whether it was given.The button just goes on.
onUnreadChanged(before, after)A check-in moved the unread count.Nothing else is told.
linksThe places in your app a link may go, for your team’s link picker (Links).Your team types paths by hand.
linkOpened(link)A link handed to handleLink is about to be followed, with a saved link’s data; or a page of your own carried a saved link or an email’s click (Links).Nothing is told.

The pages navigate is asked to show are the messenger, a new conversation, a conversation, the tickets, a ticket, the help center, a collection, an article and the preferences. You draw them all (Messenger, Help center, Preferences). The simplest way is to mount them at the paths PurrCRM writes in its own links, which CrmDestination.link(where) answers:

PathPage
/messagesThe messenger’s home
/messages/newA new conversation
/messages/<id>A conversation
/messages/tickets, /messages/tickets/<id>The tickets, a ticket
/helpThe help center
/help/collections/<slug>A collection
/help/<slug>An article
/messages/preferencesThe user’s preferences
src/crm.ts
import { CrmDestination } from "crm-sdk";
crm.host = {
...crm.host,
navigate: (where, how) => {
if (!crm.mayOpen(where)) return false; // a part switched off, or nobody signed in
const path = CrmDestination.link(where); // "/messages/42", "/help/returns"...
if (how === "open") router.replace(path);
else router.push(path);
return true;
},
};

CrmLinks holds the same paths, and CrmLinks.parse(path) answers the CrmDestination a path names, for a route of yours that reads it back. If your app keeps PurrCRM‘s pages elsewhere (in a side panel, a dialog), switch on where.place instead.

From code, crm.open(where) asks navigate with "open", and crm.show(where) with "push".

Importing the package and making the facade are safe on the server. Start it, and give it the user, only in the browser. With React (Next.js, Remix):

app/CrmStart.tsx
"use client";
import { useEffect } from "react";
import { crm } from "../src/crm";
export function CrmStart({ userId }: { userId: string | null }) {
useEffect(() => {
void crm.start().then(() => crm.handleLink(location.href));
}, []);
useEffect(() => {
crm.session(userId === null ? null : { guestId: userId });
crm.setReady(userId !== null);
}, [userId]);
return null;
}

A Value read on the server holds its starting state (no messages, nothing unread), so a component that draws it renders the same on both sides and fills in once the browser has started the facade.

await crm.dispose() stops everything: the page’s listeners, the timers and the requests in flight. Events still waiting stay in the browser for the next load. You rarely need it in an app; a test calls it after each case.

Sign users in.