JavaScript / TypeScript Quickstart

Get running with the JS SDK in 5 minutes

A copy-paste-ready guide to get up and running with the Convert JavaScript SDK in minutes.

1. Install

npm install --save @convertcom/js-sdk

Or with Yarn:

yarn add @convertcom/js-sdk

2. Import

import ConvertSDK from '@convertcom/js-sdk';

See Installation for all import patterns (ESM, CommonJS, UMD).

3. Initialize and Run

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(() => {
  // Create a user context
  const context: ContextInterface = convertSDK.createContext('user-unique-id', {
    country: 'US',
    language: 'en'
  });

  // Run a single experience
  const variation: BucketedVariation = context.runExperience('experience-key');
  console.log(variation);

  // Track a conversion
  context.trackConversion('goal-key', {
    ruleData: {
      action: 'buy'
    },
    conversionData: [
      { key: 'amount', value: 10.3 },
      { key: 'productsCount', value: 2 },
      { key: 'transactionId', value: 'transaction-unique-id' }
    ]
  });
});

What Just Happened?

  1. new ConvertSDK({ sdkKey }) fetches your project configuration from Convert's CDN.
  2. onReady() resolves when the configuration has been downloaded and the SDK is ready.
  3. createContext(userId, properties) creates a visitor session. The userId is used for deterministic bucketing -- the same user always sees the same variation.
  4. runExperience(key) evaluates targeting rules and returns the bucketed variation.
  5. trackConversion(goalKey, attributes) sends a conversion event for the given goal.

Next Steps