Web SDKMenu
On this page

Web SDK

Track signed-in customer activity and register web push with the Kirora browser SDK.

View as MarkdownOpen in ClaudeOpen in ChatGPTUpdated

Use the web SDK to track signed-in customer activity for segments and journeys. Record custom events and visits, enable page-view tracking when needed, capture consent and register the browser for push. The SDK is written in TypeScript with no dependencies and can be used with a framework or plain HTML.

Before you start

  • A website where people sign in. The SDK tracks signed-in users, so it needs to know who they are.
  • A server you control that can sign a token for the signed-in user. Every Kirora server library does it in one call; a serverless function works too.
  • The owner, admin or developer role in Kirora, to create the SDK keys.
  • For push: a site served over HTTPS (localhost works for testing), and a web push app in Kirora. See Set up push.

How it works

The SDK runs in your users’ browsers, so it never uses an API key. It uses two things instead:

  • A client key (kirora_pk_…): public, safe to put in the page. It says which workspace the events belong to.
  • A user token: signed by your server for the user who is signed in, so nobody can send events as someone else. The SDK asks your server for one at sign-in and whenever one expires.

1 Create your keys

In the dashboard, open Developer → SDK. An owner, admin or developer chooses Set up the SDK, which creates both keys. The Secret key is your token secret, shown only once: put it in your server’s environment as KIRORA_SDK_TOKEN_SECRET. The Public key is your client key (kirora_pk_…). It’s shown on the same page and goes in your site.

2 Add a token route to your server

The SDK proves who is signed in with a token from your server. With the Node.js library, the route is one call:

TypeScript
// Express
import { createUserToken } from '@kirora/node';

app.get('/kirora-token', requireSignedIn, (request, response) => {
  response.send(createUserToken(process.env.KIRORA_SDK_TOKEN_SECRET!, request.user.id));
});
TypeScript
// Next.js: app/kirora-token/route.ts
import { createUserToken } from '@kirora/node';
import { auth } from '@/auth';

export async function GET() {
  const session = await auth();
  if (!session?.user?.id) return new Response(null, { status: 401 });
  return new Response(createUserToken(process.env.KIRORA_SDK_TOKEN_SECRET!, session.user.id));
}

The Go, .NET, PHP and Laravel libraries do the same in one call. In any other language, use a JWT library: sign with HS256 and the token secret, set sub to your own id for the user (their contact’s externalId), and set exp no more than 24 hours after iat.

3 Install and start the SDK

Terminal
npm install @kirora/web    # or: pnpm add @kirora/web, yarn add @kirora/web

Create one instance for the whole site:

TypeScript
// src/kirora.ts
import { Kirora } from '@kirora/web';

/** Your server's route that signs a token for the signed-in user (step 2). */
export async function fetchKiroraToken(): Promise<string> {
  const response = await fetch('/kirora-token');
  // Throw rather than hand Kirora an error page: the SDK keeps the events and retries.
  if (!response.ok) throw new Error(`Token route returned ${response.status}`);
  return response.text();
}

export const kirora = new Kirora({
  clientKey: 'kirora_pk_…', // public: safe in the page
  fetchUserToken: fetchKiroraToken, // at sign-in, and when a token expires
  trackPageViews: true, // optional
  push: true, // optional: leave out if you send no pushes
});

4 Sign users in and out

TypeScript
import { kirora } from './kirora';

// On every page load where the user is signed in, and right after they sign in.
// The token comes from fetchUserToken; identify(token) takes one you already have.
await kirora.identify();

// Before your own sign-out.
await kirora.logout();

Nothing is sent before sign-in: events tracked earlier wait on the device and go as the user who signs in next. logout() sends what is waiting and forgets the rest.

5 Track what they do

TypeScript
kirora.track('Plan Upgraded', { plan: 'pro', seats: 5 });
kirora.track('Order Completed', { order_id: 'A-1001', total: 49.99, currency: 'USD' });

track() returns at once, since events go in batches, so call it anywhere without await. Name events as the naming guide below describes, so journeys and segments can match them.

Visits, page views and context

The SDK adds what Kirora needs to understand each event, so your own code only names what happened:

  • Context: every event carries a context object beside your own properties, saying where it happened: the page’s address, path, title and referrer, any utm_* campaign tags, the user’s locale and time zone, the visit, and a lasting id for this browser kept until its site data is cleared. Query strings are sent as they are; fragments never are. If a page’s address can hold a token or an email address, such as a password-reset link, remove it from the address before the page is tracked, for example with history.replaceState. Segments and journeys filter on your properties, not on context. See the context object.
  • Visits: a visit begins with a Session Started event that records how the visitor arrived (its path, referrer and utm_* properties), and every event in it carries the same context.sessionId. So “came from the newsletter, compared plans, left” reads as one visit. A visit ends after 30 minutes without activity, and tabs of the same site share it. Visits are on by default; trackSessions: false turns them off.
  • Page views: trackPageViews: true records Page Viewed on every page, including single-page app navigations (a change to the query string alone is not a new page). It is off by default, since every view is an event. To record page views from your own router instead, call trackPageView().

Where the law asks for consent before tracking, as in the EU and the UK, start the SDK with requireTrackingConsent: true. Nothing is tracked or stored until your consent banner says yes:

TypeScript
export const kirora = new Kirora({ /* … */ requireTrackingConsent: true });

cookieBanner.onAccept(() => kirora.setTrackingConsent(true));
cookieBanner.onReject(() => kirora.setTrackingConsent(false));

The answer is remembered on the device. setTrackingConsent(false) stops tracking and forgets events still waiting. Push consent is separate, below.

Send web push

Push is one channel that uses the same signed-in user. To add it:

  1. Create a web push app in the dashboard. See Set up push.

  2. Start the SDK with push: true.

  3. Serve kirora-sw.js from your site’s root. It must be on your own origin, so copy it into your public folder as part of your build:

    Terminal
    cp node_modules/@kirora/web/dist/kirora-sw.js public/kirora-sw.js

    If your site already has a service worker, add importScripts('https://cdn.jsdelivr.net/npm/@kirora/web/dist/kirora-sw.js') to it instead. It handles only Kirora’s pushes.

There is nothing else to copy: the SDK asks Kirora for the push app’s settings. Ask for permission from a click, since browsers allow the prompt only then:

TypeScript
enableNotificationsButton.addEventListener('click', async () => {
  if ((await kirora.requestPushPermission()) === 'granted') {
    await kirora.setPushConsent(true); // their consent to push notifications
  }
});

The browser is registered for push at identify() and when permission is granted. Browser permission is enough for a transactional push, such as an order update. Campaign and journey push also needs the user’s consent, which setPushConsent() records. Opens and clicks are reported by the service worker with no code of yours.

On iPhone and iPad, web push needs iOS 16.4 or later, and works only from your site’s Home Screen icon: ask people to add your site to their Home Screen, then open it from there. Your site needs a web app manifest with "display": "standalone" for the Home Screen app to receive push. In a regular Safari tab, requestPushPermission() returns unsupported.

React

Create the instance once, outside any component (step 3), and sign in where your own session starts:

TypeScript
import { useEffect } from 'react';
import { kirora } from './kirora';

export function KiroraSession({ userId }: { userId: string | null }) {
  useEffect(() => {
    if (userId) void kirora.identify();
  }, [userId]);
  return null;
}

// In a component
<button onClick={() => kirora.track('Invite Sent', { channel: 'email' })}>Invite</button>;

Call await kirora.logout() in your sign-out handler, before your own sign-out. React hooks are planned as a separate package, @kirora/web-react. (@kirora/react is a different package: the React builders.)

Next.js

The same, from client components ('use client'). Importing the instance during server rendering is harmless: it touches no browser API and sends nothing until identify(), which runs in an effect. Serve kirora-sw.js from public/, which Next.js serves at the site’s root.

Without a bundler

For plain HTML, Webflow or WordPress, put the loader in <head>. It stands in for the SDK until the file arrives, so calls made before then are kept and made in order:

HTML
<script>
  (function (options) {
    var kirora = (window.kirora = window.kirora || []);
    if (!Array.isArray(kirora) || kirora.options) return;
    kirora.options = options;
    ['identify', 'logout', 'track', 'trackPageView', 'setPushConsent', 'setTrackingConsent'].forEach(function (method) {
      kirora[method] = function () {
        kirora.push([method, Array.prototype.slice.call(arguments)]);
      };
    });
    var script = document.createElement('script');
    script.async = true;
    script.src = 'https://cdn.jsdelivr.net/npm/@kirora/web/dist/kirora.min.js';
    document.head.appendChild(script);
  })({ clientKey: 'kirora_pk_…', trackPageViews: true });

  kirora.track('Signup Started');
</script>

Once loaded, window.kirora is the SDK itself, and every call the loader held is made on it. A method missing from the loader’s list can’t be called before then. requestPushPermission() is not held: call it from a click once the SDK has loaded.

Options

new Kirora(options) starts the SDK. Create one instance when your site starts.

Option Required Default What it does
clientKey Yes The workspace’s public key (kirora_pk_…). It’s safe to ship in a page.
fetchUserToken No Asks your server for a signed user token. Called by identify() without a token, and when Kirora refuses an expired one.
push No Off true, or { pushAppId, serviceWorkerUrl }, to register this browser for push. pushAppId picks the push app when the workspace has several; serviceWorkerUrl is /kirora-sw.js unless set.
requireTrackingConsent No false Track and store nothing until setTrackingConsent(true).
trackSessions No true Record Session Started when a visit begins, and the visit on every event.
trackPageViews No false Record Page Viewed automatically, including single-page app navigations.
logLevel No error none, error or debug. Set debug while you build to see each event, batch and refusal in the console.
apiUrl No https://api.kirora.io For tests against a mock server.

Visits are tracked by default. Page views are recorded when you turn them on or call trackPageView(), and events when you call track(). Tracking consent, when you require it, applies to all of them. Events are queued and sent in the background, so the SDK doesn’t hold up your page’s start.

Methods

Method Returns Does
identify(token?) Promise<void> Signs the user in, with a token from fetchUserToken unless given one; registers the browser for push if allowed; sends waiting events. Throws only for the token: UserTokenError when fetchUserToken fails, or a KiroraApiError with status 401 when Kirora refuses a fresh token. A failed push registration is logged, not thrown.
logout() Promise<void> Sends what waits, stops this browser’s pushes for the user, and forgets the rest. Safe to call twice.
track(name, properties?) Nothing, at once Records an event.
trackPageView() Nothing, at once Records Page Viewed for the current page.
requestPushPermission() Promise of the answer Shows the browser’s prompt. Returns granted, denied, unanswered or unsupported.
setPushConsent(granted) Promise<void> Records the user’s consent to push notifications, which campaign and journey push needs.
setTrackingConsent(granted) Nothing, at once Records the visitor’s answer, with requireTrackingConsent.
flush() Promise<void> Sends waiting events now. Rarely needed.

Delivery and errors

  • Batches: events go at once when 20 are waiting, otherwise every 30 seconds and when the tab is hidden, in batches of up to 100. Up to 1,000 are kept across reloads and tabs; beyond that, the oldest are dropped.
  • Retries: when the browser is offline or Kirora is busy, the SDK retries with doubling gaps up to 5 minutes, never sooner than the Retry-After Kirora sends. Each event carries an idempotency key, so a retry is recorded once for as long as the event is kept (see Idempotency and Retention).
  • Errors: Kirora’s refusals are KiroraApiError, with status, code and retryAfterMs. A failing fetchUserToken is logged as UserTokenError, and the events wait. track() never throws: an event Kirora refuses is logged (see logLevel) and the others still go.
  • Plan limit: past your plan’s tracked events for the month, Kirora refuses further events with 403 PLAN_LIMIT_REACHED and the SDK drops them. Sign-in and push still work.

Browsers, storage and network

  • Browsers: Chrome 80, Firefox 74, Safari 14 and later.
  • On the device: events waiting to be sent are kept in localStorage, as are the visitor’s tracking consent, the device’s id, the current visit and the push registration. Their keys start with kirora:. If localStorage is blocked, they are kept in memory for the visit.
  • Cookie: the device and visit ids are also kept in a first-party cookie on your site’s root domain, so one visitor stays one device across your subdomains.
  • Network: the SDK calls only the Kirora API, at https://api.kirora.io unless you set apiUrl, and your own token route; a push subscription goes through the browser’s own push service. If you use a Content Security Policy, allow that address in connect-src, and the CDN in script-src if you load the SDK from it.

Naming events

Journeys, segments, conversion goals and goals match event names exactly, so settle them once:

  • A thing, then what happened to it, in the past tense and Title Case: Plan Upgraded, Invoice Paid, Signup Started. Not upgrade, clickedButton or PLAN_UPGRADE.
  • What the user did, not the screen it happened on: Order Completed with { "source": "checkout" }, not Checkout Page Button Clicked.
  • Details in properties, not the name: one Plan Upgraded with { "plan": "growth" }, not Growth Plan Upgraded.
  • Commerce events already have names: Product Viewed, Product Added, Order Completed and the rest of the e-commerce events.
  • Property names in lowercase snake_case: order_id, plan_name. Fields the API defines, such as context.sessionId, stay camelCase. See property names.

Names are case-sensitive, and a workspace has at most 1,000 of them: the full rules are in Events.

SDK limitations

The web SDK doesn’t provide:

  • listeners for notification clicks, or for pushes that arrive while the page is open;
  • tags or aliases set from the browser;
  • in-app messages, location or outcomes.

Profile fields are set from your server with the API’s identify a contact. Conversions are measured by the conversion goals on campaigns and journeys.

Frequently asked questions

Why does the SDK need a token and not just the user’s id?

Anyone can read a page’s code. If the SDK accepted a plain id, anyone could send events, or register for pushes, as any of your users. A token signed by your server proves the user really is signed in, and keeps your API key and token secret off the page.

What happens to events tracked before sign-in?

They wait in the browser and go as the next user to sign in. Nothing is sent anonymously.

What does a Free workspace get from the SDK?

Everything: sign-in, push, and events, page views and visits, up to the Free plan’s tracked events a month. Past that, Kirora refuses further events until next month and the SDK drops them.

Next steps