Skip to content

CodeExamples

Ahmed Abbas edited this page Apr 7, 2026 · 1 revision

JavaScript SDK — Code Examples

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:

Parameter Type Required Description
attributes object No See 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:

Parameter Type Required Description
experienceKey string Yes The experience's unique key
attributes object No See 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:

Parameter Type Required Description
attributes object No See 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:

Parameter Type Required Description
featureKey string Yes The feature's unique key
attributes object No See 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:

Parameter Type Required Description
goalKey string Yes The goal's unique key
attributes object No Conversion attributes (see below)

Attributes:

Property Type Description
ruleData object Key-value pairs used for goal rule matching
conversionData Array<object> Transaction data entries. Each entry accepts:
amount (number) - order value
productsCount (number) - order quantity
transactionId (string | number) - unique transaction identifier
conversionSetting object Tracking 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:

Parameter Type Required Description
segmentsKeys string[] Yes List of segment keys to evaluate
visitorProperties object No Key-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:

Parameter Type Required Description
segments object Yes Key-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:

Parameter Type Required Description
visitorProperties object Yes Key-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:

Parameter Type Required Description
key string Yes Entity key
entityType EntityType Yes One 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:

Parameter Type Required Description
id number Yes Entity numeric ID
entityType EntityType Yes Same 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:

Parameter Type Required Description
reason string No Custom 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

Event Triggered By Callback Data
ready SDK initialization complete null
bucketing Running experience(s) { visitorId: string, experienceKey: string, variationKey: string }
Running feature(s) { visitorId: string, experienceKey: string, featureKey: string, status: string }
conversion Tracking a conversion { visitorId: string, goalKey: string }
location.activated Location rules matched { visitorId: string, location: { id: string, name: string, key: string } }
location.deactivated Location rules no longer matched (only if activated earlier) { visitorId: string, location: { id: string, name: string, key: string } }
config.updated Configuration refreshed from CDN null

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.

Clone this wiki locally