Code Examples

Complete JS/TS examples for all SDK methods

Complete code examples for all SDK methods. All examples are extracted from the official SDK documentation.

Running Experiences

Run All Active Experiences

Loops through each active experience, evaluates targeting rules, and returns the selected variation for each.

const variations: BucketedVariation[] = userContext.runExperiences();

// With attributes:
const variations: BucketedVariation[] = userContext.runExperiences({
  locationProperties: { url: '/pricing' },
  visitorProperties: { plan: 'pro' },
  enableTracking: true
});

Parameters:

ParameterTypeRequiredDescription
attributesobjectNoSee Attributes Object

Returns: Array<BucketedVariation>

Full Example

import type {
  ConvertInterface,
  ConvertConfig,
  ContextInterface,
  BucketedVariation
} from '@convertcom/js-sdk';
import ConvertSDK from '@convertcom/js-sdk';

const config: ConvertConfig = {
  // full configuration options
};

const convertSDK: ConvertInterface = new ConvertSDK(config);
convertSDK.onReady().then(() => {
  const context: ContextInterface = convertSDK.createContext('user-unique-id');
  const variations: BucketedVariation[] = context.runExperiences();
  console.log(variations);
});

Run a Single Experience

Evaluates a single experience by its key.

const variation: BucketedVariation = userContext.runExperience('experience-key');

// With attributes:
const variation: BucketedVariation = userContext.runExperience('experience-key', {
  locationProperties: { url: '/' },
  visitorProperties: { country: 'US' }
});

Parameters:

ParameterTypeRequiredDescription
experienceKeystringYesThe experience's unique key
attributesobjectNoSee Attributes Object

Returns: BucketedVariation (see Data Model > BucketedVariation)

Full Example

import type {
  ConvertInterface, ConvertConfig, ContextInterface, BucketedVariation
} from '@convertcom/js-sdk';
import ConvertSDK from '@convertcom/js-sdk';

const convertSDK: ConvertInterface = new ConvertSDK({
  sdkKey: 'xxx'
} as ConvertConfig);

convertSDK.onReady().then(() => {
  const context: ContextInterface = convertSDK.createContext('user-unique-id');
  const variation: BucketedVariation = context.runExperience('experience-key');
  console.log(variation);
});

Running Features

Features are resolved through variations of relevant experiences. See Data Model > How Features Are Resolved for the full resolution chain.

Run All Features

Returns all features with their status and variable values for the visitor.

const features: BucketedFeature[] = userContext.runFeatures();

// With attributes:
const features: BucketedFeature[] = userContext.runFeatures({
  locationProperties: { url: '/dashboard' },
  visitorProperties: { tier: 'premium' },
  typeCasting: true
});

Parameters:

ParameterTypeRequiredDescription
attributesobjectNoSee Attributes Object, plus:
typeCasting: boolean - auto-convert values to the variable's defined type (default: true)

Returns: Array<BucketedFeature>

Full Example

import type {
  ConvertInterface,
  ConvertConfig,
  ContextInterface,
  BucketedFeature
} from '@convertcom/js-sdk';
import ConvertSDK from '@convertcom/js-sdk';

const config: ConvertConfig = {
  // full configuration options
};

const convertSDK: ConvertInterface = new ConvertSDK(config);
convertSDK.onReady().then(() => {
  const context: ContextInterface = convertSDK.createContext('user-unique-id');
  const features: BucketedFeature[] = context.runFeatures();
  console.log(features);
});

Run a Single Feature

Returns a single feature's status and variable values for the visitor.

const feature: BucketedFeature = userContext.runFeature('feature-key');

// With attributes and experience filter:
const feature: BucketedFeature = userContext.runFeature('feature-key', {
  locationProperties: { url: '/settings' },
  visitorProperties: { role: 'admin' },
  typeCasting: true,
  experienceKeys: ['specific-experience-key']
});

Parameters:

ParameterTypeRequiredDescription
featureKeystringYesThe feature's unique key
attributesobjectNoSee Attributes Object, plus:
typeCasting: boolean - auto-convert values to the variable's defined type (default: true)
experienceKeys: string[] - limit evaluation to specific experiences only

Returns: BucketedFeature (see Data Model > BucketedFeature)

Full Example

import type {
  ConvertInterface, ConvertConfig, ContextInterface, BucketedFeature
} from '@convertcom/js-sdk';
import ConvertSDK from '@convertcom/js-sdk';

const convertSDK: ConvertInterface = new ConvertSDK({
  sdkKey: 'xxx'
} as ConvertConfig);

convertSDK.onReady().then(() => {
  const context: ContextInterface = convertSDK.createContext('user-unique-id');
  const feature: BucketedFeature = context.runFeature('feature-key');

  if (feature && feature.status === 'enabled') {
    console.log('Feature is enabled with variables:', feature.variables);
  }
});

Tracking Conversions

Sends a conversion event for a goal. The decision is made against the goal's configured triggering rules.

userContext.trackConversion('goal-key', {
  ruleData: {
    action: 'buy'
  },
  conversionData: [
    { key: 'amount', value: 10.3 },
    { key: 'productsCount', value: 2 },
    { key: 'transactionId', value: 'transaction-unique-id' }
  ],
  conversionSetting: {
    forceMultipleTransactions: false
  }
});

Parameters:

ParameterTypeRequiredDescription
goalKeystringYesThe goal's unique key
attributesobjectNoConversion attributes (see below)

Attributes:

PropertyTypeDescription
ruleDataobjectKey-value pairs used for goal rule matching
conversionDataArray<object>Transaction data entries. Each entry accepts:
amount (number) - order value
productsCount (number) - order quantity
transactionId (string | number) - unique transaction identifier
conversionSettingobjectTracking settings:
forceMultipleTransactions (boolean) - whether to accumulate revenue for the same visitor

Returns: void

Full Example

import type {
  ConvertInterface,
  ConvertConfig,
  ContextInterface
} from '@convertcom/js-sdk';
import ConvertSDK from '@convertcom/js-sdk';

const config: ConvertConfig = {
  // full configuration options
};

const convertSDK: ConvertInterface = new ConvertSDK(config);
convertSDK.onReady().then(() => {
  const context: ContextInterface = convertSDK.createContext('user-unique-id');
  context.trackConversion('goal-key', {
    ruleData: {
      action: 'buy'
    },
    conversionData: [
      {
        key: 'amount',
        value: 10.3
      },
      {
        key: 'productsCount',
        value: 2
      },
      {
        key: 'transactionId',
        value: 'transaction-unique-id'
      }
    ],
    conversionSetting: {
      forceMultipleTransactions: false
    }
  });
});

Segments

Run Custom Segments

Evaluates segment rules and updates custom segments in the user context.

userContext.runCustomSegments(['segment-key-1', 'segment-key-2'], {
  enabled: true
});

Parameters:

ParameterTypeRequiredDescription
segmentsKeysstring[]YesList of segment keys to evaluate
visitorPropertiesobjectNoKey-value pairs used for segment matching

Returns: void

Full Example

import type {
  ConvertInterface,
  ConvertConfig,
  ContextInterface
} from '@convertcom/js-sdk';
import ConvertSDK from '@convertcom/js-sdk';

const config: ConvertConfig = {
  // full configuration options
};

const convertSDK: ConvertInterface = new ConvertSDK(config);
convertSDK.onReady().then(() => {
  const context: ContextInterface = convertSDK.createContext('user-unique-id');
  context.runCustomSegments(['segment-key'], {
    enabled: true
  });
});

Set Default Segments

Permanently updates the visitor's default segments for reporting. Only the following properties are included in Convert Reports:

  • browser
  • devices
  • source
  • campaign
  • visitorType
  • country
userContext.setDefaultSegments({
  country: 'US',
  browser: 'chrome',
  devices: 'desktop'
});

Parameters:

ParameterTypeRequiredDescription
segmentsobjectYesKey-value pairs merged with the initial visitor properties

Returns: void


Visitor Properties

Update Visitor Properties

Permanently updates all visitor properties used in audience evaluation.

userContext.updateVisitorProperties({
  weather: 'rainy',
  plan: 'enterprise'
});

Parameters:

ParameterTypeRequiredDescription
visitorPropertiesobjectYesKey-value pairs merged with the initial visitor properties

Returns: void

Visitor properties can also be updated inline when calling any experience/feature method by setting updateVisitorProperties: true in the attributes object:

const variation = userContext.runExperience('experience-key', {
  visitorProperties: { weather: 'rainy' },
  updateVisitorProperties: true
});

Config Entity Lookup

Get Config Entity by Key

Find a single entity in the project configuration by its key.

import ConvertSDK, {EntityType} from '@convertcom/js-sdk';
import type {Experience} from '@convertcom/js-sdk';

const experience: Experience = userContext.getConfigEntity(
  'experience-key',
  EntityType.EXPERIENCE
);

Parameters:

ParameterTypeRequiredDescription
keystringYesEntity key
entityTypeEntityTypeYesOne of: EntityType.AUDIENCE, EntityType.LOCATION, EntityType.SEGMENT, EntityType.FEATURE, EntityType.GOAL, EntityType.EXPERIENCE, EntityType.VARIATION

Returns: The matching entity object or null.

Get Config Entity by ID

Find a single entity in the project configuration by its numeric id.

import ConvertSDK, {EntityType, VariationChangeType} from '@convertcom/js-sdk';
import type {BucketedVariation, Feature, VariationChange} from '@convertcom/js-sdk';

const variation: BucketedVariation = userContext.runExperience('experience-key');
const changesData: VariationChange = variation.changes.find(
  ({type}) => type === VariationChangeType.FULLSTACK_FEATURE
);
const feature: Feature = userContext.getConfigEntityById(
  changesData.data.feature_id,
  EntityType.FEATURE
);

Parameters:

ParameterTypeRequiredDescription
idnumberYesEntity numeric ID
entityTypeEntityTypeYesSame values as getConfigEntity above

Returns: The matching entity object or null.


Releasing Queues

The SDK batches tracking events and sends them periodically (configured via events.batch_size and events.release_interval). You can manually flush all pending queues.

const variations: BucketedVariation[] = userContext.runExperiences();

// Manually release all pending queues (e.g. on component unmount, button click, navigation)
userContext.releaseQueues().then(() => {
  console.log('all pending queues have been released');
});

// With a reason (for debugging)
userContext.releaseQueues('page-exit');

Parameters:

ParameterTypeRequiredDescription
reasonstringNoCustom message for debugging

Returns: Promise<void>

This is especially important in short-lived environments like Cloudflare Workers where the event batch timer may not have time to fire. See Cloudflare Workers for edge-specific patterns.


Events

The SDK emits events that you can subscribe to for logging, analytics integrations, or debugging.

Available Events

EventTriggered ByCallback Data
readySDK initialization completenull
bucketingRunning experience(s){ visitorId: string, experienceKey: string, variationKey: string }
Running feature(s){ visitorId: string, experienceKey: string, featureKey: string, status: string }
conversionTracking a conversion{ visitorId: string, goalKey: string }
location.activatedLocation rules matched{ visitorId: string, location: { id: string, name: string, key: string } }
location.deactivatedLocation rules no longer matched (only if activated earlier){ visitorId: string, location: { id: string, name: string, key: string } }
config.updatedConfiguration refreshed from CDNnull

Subscribing to Events

import ConvertSDK, {SystemEvents} from '@convertcom/js-sdk';
import type {
  ConvertInterface, ConvertConfig, ContextInterface, Experience, Variation
} from '@convertcom/js-sdk';

const convertSDK: ConvertInterface = new ConvertSDK({
  sdkKey: 'xxx'
} as ConvertConfig);

// Ready event
convertSDK.on(SystemEvents.READY, function (res, err) {
  if (err) {
    console.error(err);
  }
});

// Bucketing event (e.g. for GA integration)
convertSDK.on(
  SystemEvents.BUCKETING,
  function ({visitorId, experienceKey, variationKey, featureKey, status}, err) {
    if (err) {
      console.error(err);
    } else {
      console.log(visitorId, experienceKey, variationKey, featureKey, status);

      // Example: Google Analytics integration
      const experienceName = context.getConfigEntity(
        experienceKey, EntityType.EXPERIENCE
      ).name;
      const variationName = context.getConfigEntity(
        variationKey, EntityType.VARIATION
      ).name;
      gtag('event', 'convert_bucketing', {
        experienceName,
        variationName
      });
    }
  }
);

// Conversion event
convertSDK.on(SystemEvents.CONVERSION, function ({visitorId, goalKey}, err) {
  if (err) {
    console.error(err);
  } else {
    console.log(visitorId, goalKey);
  }
});

// Config updated event
convertSDK.on(SystemEvents.CONFIG_UPDATED, function (res, err) {
  if (err) {
    console.error(err);
  }
});

See EventManager for how the pub/sub system works internally, including deferred events.


Persistent DataStore

You can provide your own DataStore to make bucketing persistent across sessions. The DataStore interface requires two methods: set and get.

import type {ConvertInterface, ConvertConfig} from '@convertcom/js-sdk';
import ConvertSDK from '@convertcom/js-sdk';

class CustomDataStore {
  #data = {};

  get(key) {
    if (!key) return this.#data;
    return this.#data[key.toString()];
  }

  set(key, value) {
    if (!key) throw new Error('Invalid CustomDataStore key!');
    this.#data[key.toString()] = value;
  }
}

const dataStore = new CustomDataStore();
const convertSDK: ConvertInterface = new ConvertSDK({
  sdkKey: 'xxx',
  dataStore
} as ConvertConfig);

Without a DataStore, bucketing decisions are only kept in-memory for the current session. With a DataStore, the SDK reads from and writes to it via a DataStoreManager wrapper (see DataManager for details).

For Cloudflare Workers environments, use the KVDataStore from @convertcom/js-sdk-cloudflare. See Cloudflare Workers for details.