Skip to main content

Getting Started

Install the SDK

Once your Web Console is setup and you have created some experiments, you can install our SDKs through your package manager, a CDN or by directly importing it.

NPM

npm install --save @absmartly/javascript-sdk

Direct Import

<script src="<YOUR-HOSTNAME>/absmartly.min.js"></script>
caution

ABsmartly’s Javascript SDK depends on support for a native ES6 promise implementation. If your environment does not support ES6 promises, you can polyfill.

Import and Initialize the SDK

Once the SDK is installed, it can be initialized in your project.

info

The following examples assume that an Api Key with SDK permissions, an Application, and an Environment have been created in the ABsmartly Web Console.

// ES6 Modules
import absmartly from "@absmartly/javascript-sdk";

// For commonJS, use:
// const absmartly = require("@absmartly/javascript-sdk");

const sdk = new absmartly.SDK({
endpoint: "https://your-company.absmartly.io/v1",
apiKey: process.env.ABSMARTLY_API_KEY,
environment: process.env.NODE_ENV,
application: process.env.APPLICATION_NAME,
});

SDK Options

ConfigTypeRequired?DefaultDescription
endpointstringundefinedThe URL to your API endpoint. Most commonly "your-company.absmartly.io"
apiKeystringundefinedYour API key which can be found on the Web Console.
environment"production" or "development"undefinedThe environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure.
applicationstringundefinedThe name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running.
retriesnumber5The number of retries before the SDK stops trying to connect.
timeoutnumber3000An amount of time, in milliseconds, before the SDK will stop trying to connect.
eventLogger(context, eventName, data) => voidSee Using a Custom Event Logger belowA callback function which runs after SDK events.

Using a Custom Event Logger

The ABsmartly SDK can be instantiated with an event logger used for all contexts. In addition, an event logger can be specified when creating a particular context, in the createContext call options. The example below illustrates this with the implementation of the default event logger, used if none is specified.

const sdk = new absmartly.SDK({
endpoint: "https://sandbox-api.absmartly.com/v1",
apiKey: process.env.ABSMARTLY_API_KEY,
environment: process.env.NODE_ENV,
application: process.env.APPLICATION_NAME,
eventLogger: (context, eventName, data) => {
if (eventName == "error") {
console.error(data);
}
},
});

The data parameter depends on the type of event. Currently, the SDK logs the following events:

eventNamewhendata
"error"Context receives an errorerror object thrown
"ready"Context turns readydata used to initialize the context
"refresh"Context.refresh() method succeedsdata used to refresh the context
"publish"Context.publish() method succeedsdata sent to the ABsmartly event collector
"exposure"Context.treatment() method succeeds on first exposureexposure data enqueued for publishing
"goal"Context.track() method succeedsgoal data enqueued for publishing
"finalize"Context.finalize() method succeeds the first timeundefined

Create a New Context Request

In order to start linking your experiments from the Web Console to your application, you will need to create a context. When you instantiate a context, you should pass all known characteristics of the current user. These characteristics are known as "units".

You can use anything as a unit. For example, you can pass an internal user id or email address. You could also pass a device_id that you store in a first- party cookie or a mobile application UUID.

Keep In Mind

The units that you pass must first be declared on your ABsmartly Web Console by going to Settings -> Units

caution

Experiments that are tracked by a unit which is not passed here will be turned off in this request and the control treatment will be shown instead.

Create A New Context With Raw Promises

// define a new context request
const request = {
units: {
userId: "123",
session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8",
email: "[email protected]", // strings will be hashed
deviceId: "345",
},
};

const context = sdk.createContext(request);

context
.ready()
.then((response) => {
console.log("ABSmartly Context ready!");
})
.catch((error) => {
console.log(error);
});

Create A New Context With Async/Await

// define a new context request
const request = {
units: {
userId: "123",
session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8",
email: "[email protected]", // strings will be hashed
deviceId: "345",
},
};

const context = sdk.createContext(request);

try {
await context.ready();
console.log("ABSmartly Context ready!");
} catch (error) {
console.log(error);
}

Create A New Context With Pre-Fetched Data

When doing full-stack experimentation with ABsmartly, we recommend only creating a context once on the server-side. Creating a context involves a round-trip to the ABsmartly event collector. We can avoid repeating the round-trip on the client-side by sending the server-side data embedded in the first document, for example, by rendering it on the template. We can then initialize the ABsmartly context on the client-side directly with it.

// In your server-side code
const serverSideParams = {
units: {
user_id: '123',
anonymous_id: '456',
session_id: '789',
// ...
},
};

const serverSideContext = sdk.createContext(serverSideParams);

await serverSideContext.ready();

const serverSideData = serverSideContext.data();

// In your client-side code
const clientSideOptions = {
publishDelay: 100, // ms
};

const clientSideContext = sdk.createContextWith(serverSideParams, serverSideData, clientSideOptions);

Refreshing the Context with Fresh Experiment Data

For long-running single-page-applications (SPA), the context is usually created once when the application is first reached. However, any experiments being tracked in your production code, but started after the context was created, will not be triggered. To mitigate this, we can use the refreshInterval option when creating the context.

const request = {
units: {
session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8",
},
};

const context = sdk.createContext(request, {
refreshInterval: 5 * 60 * 1000,
});

Alternatively, the refresh() method can be called manually. The refresh() method pulls updated experiment data from the ABsmartly collector and will trigger recently started experiments when treatment() is called again.

setTimeout(async () => {
try {
context.refresh();
} catch (error) {
console.error(error);
}
}, 5 * 60 * 1000);

HTTP request timeout

It is possible to set a timeout per individual HTTP request, overriding the global timeout set for all request when instantiating the SDK object.

Here is an example of setting a timeout only for the createContext request.

const context = sdk.createContext(
request,
{
refreshInterval: 5 * 60 * 1000,
},
{
timeout: 1500,
}
);

HTTP Request cancellation

Sometimes it is useful to cancel an inflight HTTP request, for example, when the user is navigating away. The ABsmartly SDK also supports a cancellation via an AbortSignal. An implementation of AbortController is provided for older platforms, but will use the native implementation where available.

Here is an example of a cancellation scenario.

const controller = new absmartly.AbortController();
const context = sdk.createContext(
request,
{
refreshInterval: 5 * 60 * 1000,
},
{
signal: controller.signal,
}
);

// abort request if not ready after 1500ms
const timeoutId = setTimeout(() => controller.abort(), 1500);

await context.ready();

clearTimeout(timeoutId);