Skip to main content

Browser SDK

This guide explains how to integrate an mtribes Space into your web application.

You'll learn how to synchronize changes from your Space into your codebase using our CLI's code generation, and how to use this code to control the UX of your end users.

Sample apps

Check out our sample apps covering vanilla JavaScript, React and Angular to fast-track your integration.

Requirements#

  1. A web project ready to integrate with mtribes
  2. An mtribes Space with at least one Collection and Experience
  3. The mtribes CLI installed
  4. JavaScript or TypeScript code generated for your Space

Our SDK is designed for use in modern web applications, which use code bundlers such as Webpack, Rollup or Parcel.

If you're using TypeScript, we officially support back to v3.4 but may be able to work with even earlier versions.

We use Promises. These are widely supported but Polyfills are available when targeting older browsers. See our browser support section for more details.

Browsers only

This guide is for browser based JavaScript or TypeScript projects and is not compatible with Node.js

Code integration#

With your Space code generated, you're ready to integrate mtribes into your web application.

In the code examples which follow, we'll build out an example Space containing:

  1. A homepage Collection, which contains:
    1. A banner Experience
    2. A body Section, which supports:
      1. Hero Experience types
      2. Carousel Experience types

The generated code is output to ./src/mtspace/example.

Don't worry if this isn't clear yet, as it will make more sense after we run through some examples.

Client initialization#

The mtribes Client is a top-level object for configuring your mtribes SDK.

A Client instance is generated along with your Space integration code and can be imported from the output location.

Before using the SDK, first initialize the mtribes Client with the API key of the mtribes Environment you wish to target.

You can find Environment API keys under your Space settings page.

import { client } from "./src/mtspace/example";
// when deploying your application, include the appropriate// mtribes api key in your settings for the environment// being targeted.import { mtribesApiKey } from "./app-settings";
client.init({  apiKey: mtribesApiKey,});

Client configuration#

The mtribes Client will expose some optional settings. We've given these sensible defaults, but you can override them to further harmonize mtribes with your application.

Example: Disable session locking to enable live Section and Experience change events during a user session.

client.sessionLock = false;

It's best to configure the Client before starting the session, but configuration can be adjusted at anytime.

See the full list of client configuration options.

Session start#

Before accessing an Experience, it's important to start a session for the active user, so we can serve them personalized states.

We represent an mtribes session via the session object, which you can import from your generated code.

import { session } from "./src/mtspace/example";

Anonymous user#

Start a session for an anonymous user.

await session.start();

This should be done:

  • on app launch if the user is anonymous
  • when a user logs out

It's important to wait for the completion of start() before accessing Experiences and Sections.

Logged in user#

Starting a session for a logged in user is similar to an anonymous one, except you must provide their unique identifier.

await session.start({ userId: user.id });

This should be done:

  • on app launch if the user is already logged in
  • when a user logs in

Again, wait for the completion of start() before accessing Experiences and Sections.

Personal Information

A user ID should be opaque and not personally identifiable. For example, you should avoid email addresses, social security numbers or similarly personal information.

If you don't have an opaque ID for a user, you can use a secure hashing algorithm such as SHA256 to encode it before passing it to session.start.

Contextual properties#

When starting a session, you can also provide fields with values specific to the user. These open up powerful Tribe targeting options in the mtribes platform.

Example 1: Start a session for an anonymous user with a contextual property of campaign.

await session.start({  fields: {    campaign: campaignId,  },});

Example 2: Start a session for a logged in user with a contextual property of subscription.

await session.start({  userId: user.id,  fields: {    subscription: user.subscription,  },});

We currently support the following contextual property types.

  • boolean: true or false
  • number: e.g. 842, 0.332
  • string: e.g. "gold"
  • date: ISO-8601 UTC string encoded timestamp e.g. "2020-12-02T02:45:02.076Z" This must include the date and time.
Property Limits

A maximum of 50 contextual properties can be active at one time. You can remove unused properties to make room for new ones in the contextual property settings page.

To avoid exceeding these limits or sending PII by mistake, we recommend selecting specific contextual properties to include when starting a session.

Experience access#

With the session primed, you can now check whether Experiences modeled in the Space are enabled for a user, and if so, what custom data properties have been defined for them.

// generated code includes the set of Space Collectionsimport { collections } from "./src/mtspace/example";
// access the banner Experience from the homepage Collectionconst { banner } = collections.homepage;
// example of a render function in your app to present a Bannerfunction renderBanner() {  // only render the banner Experience if it's enabled  if (banner.enabled) {    // access customized data for the banner    const { imageURL } = banner.data;    drawBanner(imageURL);  }}

Section iteration#

Sections contain an array of child Experiences defined at runtime by a Scheduler in the mtribes platform. You can iterate over these child Experiences and render each in turn, depending on its type.

Each Section defines its supported Experience types. You can use these as switch cases and render appropriately given an Experience kind.

// generated code includes the set of Space Collectionsimport { collections } from "./src/mtspace/example";
// access the body Section from the homepage Collectionconst { body } = collections.homepage;
// example of a render function in your app to render// a dynamic list of UI elements in the body areafunction renderBody() {  // render each child Experience of the 'body' Section in order  for (const exp of body.children) {    // if an Experience is disabled we'll skip it    if (!exp.enabled) continue;
    switch (exp.kind) {      case body.supported.Hero:        drawHero(exp.data);        break;      case body.supported.Carousel:        drawCarousel(exp.data);        break;    }  }}

Change events#

The state of an Experience or Section may change for a user during their session. You can monitor these changes and reflect them in your code.

Live updates

If you want published change events to fire during a user's session, then you'll need to set Client.sessionLock to false. By default session locking is enabled to avoid published changes negatively impacting UX.

// generated code includes the set of Space Collectionsimport { collections } from "./src/mtspace/example";
// access the members of the homepage Collectionconst { banner, body } = collections.homepage;
// when the banner Experience changes, re-render itbanner.changed.add(() => renderBanner());
// when the body Section changes, re-render itbody.changed.add(() => renderBody());

Behavior tracking#

To help you gather user analytical behavioral patterns associated with an Experience, we expose a track function.

Analytic events support a Category and Action to help with event classification. These properties are encoded as a string in the format <category>/<action>. If only <action> is provided, a default Category of user is assumed.

Event naming

A category or action must each be between 1 and 100 characters.

Valid characters must be in the following set: A-Za-z0-9_-

Any event which fails validation is ignored.

Do Not Track

Our web SDK respects the Do Not Track browser setting. When enabled by a user, all SDK analytics are disabled.

Here are a few examples from our banner Experience above.

import { collections } from "./src/mtspace/example";
// access the banner Experience from the homepage Collectionconst { banner } = collections.homepage;
// track an ad viewed event// category 'ad', action 'viewed'banner.track("ad/viewed");
// track a sign in event// category 'user' (default), action 'signed_in'banner.track("signed_in");
// optional details can be provided including// a contextual label and integer valuebanner.track("item/clicked", {  label: "Winter Specials",  value: 1,});

Trusted Identity#

Trusted Identity helps ensure the authenticity of users identified into your mtribes Space. View our comprehensive Trusted Identity guide to understand what this is and how to enable it.

Once you have a hashed user signature returned from your server, you should pass this as an option when starting a session for a logged in user.

await session.start({  userId: user.id,  signed: signature,});

Configuration options#

See below a list of all available client configuration options.

sessionLock#

Client.sessionLock: true | false | 'memory' | 'session';

Defaults to true.

Determines whether the session lock cache is enabled or not.

When true, the default backing store of the cache will be memory. This means browser refreshing will cause the cache to be purged, and the updated Experience and Section states will be made available.

If you’d like an even more consistent UX for your users, you can maintain the original Section or Experience state over the life of a session, even on page refresh. To do this, set this config property to session which will use local session persistence.

When set to 'false', all session caching is disabled. Published updates from mtribes will be pushed in real-time to connected clients. We’d recommend you only use this in development, or when dealing with scheduled updates that need to be real-time. In all other cases, this can negatively impact the user experience, as published changes can alter the UI a user is currently engaging with.

waitForMsec#

Client.waitForMsec: number;

Defaults to 1200 milliseconds (1.2 seconds).

When either session.identify or session.anonymize are called, a network request is made to prime the session with Experience and Section states for that user.

Both of these calls return a Promise which should be awaited until the session is ready to be accessed.

The priming request is designed to return quickly, however, poor network conditions may impact response times.

To ensure that UX is not adversely impacted due to unexpected network delays, you can set waitForMsec to cap the number of milliseconds before the Promise is resolved and the application can begin accessing Experience and section states.

If the defined wait time has elapsed, then accessing the session's Experience and Section states will target code generated fallbacks. In the case that the same user was recently active, their session will target previously primed session states.

Priming will continue in the background if wait time elapses and populate the session state once loaded.

userTracking#

Client.userTracking: boolean;

Defaults to true.

Determines whether user behavioral tracking events may be sent to the mtribes platform.

Analytics events are needed to support meaningful insights and intelligent targeting decisions in mtribes.

Set this option to false if the user did not give tracking consent.

includeTribes#

Client.includeTribes: boolean;

Defaults to false.

When true, Tribes for the current user will be evaluated when their session starts. Any Tribes the current user belongs to will have their IDs exposed via session.tribeIds

log#

Client.log: Logger;

Sets a custom logger to consume and manage internal logs from the SDK.