NAV
Javascript (ES6)

Introduction to NodeJS & JS SDK

Welcome to the Flagship JS SDK documentation!

The following documentation helps you to run Flagship on your JS environment (client-side or server-side).

Prerequisites

Good to know

Getting Started

// 1. Install the node module:
npm install @flagship.io/js-sdk

// 2. Import it in your code:
import flagship from "@flagship.io/js-sdk"; // ES6 ++

const flagship = require("@flagship.io/js-sdk"); // ES5

// 3. Initialize
const sdk = flagship.start("YOUR_ENV_ID", { /* sdk settings */ });

// 4. Create a visitor:
const visitorInstance = sdk.newVisitor("YOUR_VISITOR_ID",{
    //...
    some: "VISITOR_CONTEXT",
    //...
});

visitorInstance.on('ready', () => {
    console.log('visitorInstance is ready ! ✨')
});

// 5. Get modifications:
const {btnColor, btnText} = visitorInstance.getModifications([{key: "btnColor", defaultValue: "#ff0000"}, {key: "btnText", defaultValue: "Wahoo !"}]);

console.log(btnColor); // output: "#fff"
console.log(btnText); // output: "Awesome !"

// This is one of the basic workflow you can achieve with the SDK. πŸ™‚

There are 5 steps to follow to get started with the JS/NodeJS SDK. You can check some code example on the right.

  1. Install the node module
  2. Import it in your code
  3. Initialize
  4. Create a visitor
  5. Get modifications

SDK Settings

Here are all available settings you can set on the SDK.

Those settings can be setup using start function (sample inside).

Below the attributes you can set inside the SDK settings object:

Argument Type Default Description
fetchNow boolean false Decide to fetch automatically modifications data when creating a new FlagshipVisitor.
activateNow boolean false Decide to trigger automatically the data when creating a new FlagshipVisitor.
NOTE: when set to true, it will implicitly set fetchNow=true as well.
enableConsoleLogs boolean false Enable it to display logs on the console when SDK is running.
This will display logs such as Warnings, Errors, Fatal errors and Info.
nodeEnv string 'production' If value is other than production, it will also display Debug logs.
flagshipApi string 'https://decision-api.flagship.io/v1/' This setting can be useful in further scenario:
- If you need to mock the API for tests such as end to end.
- If you want to move to an earlier version of the Flagship API (v2, v3,...).
apiKey string null If you want to use the Decision API V2, you must contact the support team so they'll provide you an API Key to authenticate the calls.
initialModifications Array(object) null This is an array of modifications where each element must be same shape as element inside "campaigns" attribute.
Providing this prop avoid the SDK to have an empty cache during first initialization.
If the shape of an element is not correct, an error log will give the reason why.

JS SDK Features

Summary

Don’t hesitate to have a look to Flagship Getting Started as well to understand how the product is working. 😊

flagshipSdk object

Flagship class

FlagshipVisitor class

Shape of possible hits to send


flagshipSdk object

start

Demo:

const sdk = flagship.start("YOUR_ENV_ID",
{
    enableConsoleLogs: true,
    fetchNow: false,
});
Attribute Type Default Description
envId string Required Your Flagship environment id.
config object defaultConfig Setup SDK settings. It will override attributes from default configuration so you just need to specify the attributes you need to change. You can check config attributes here.

Flagship class

Summary

newVisitor

Demo:

const visitorInstance = sdk.newVisitor("YOUR_VISITOR_ID",{
    //...
    some: "VISITOR_CONTEXT",
    //...
});

visitorInstance.on('ready', () => {
    console.log('visitorInstance is ready ! ✨')
});
Attribute Type Default Description
id string Required Your Flagship visitor id.
context object {} Your Flagship visitor context you'll set inside attributes. It should match those defined in your campaigns to target your users on it.

FlagshipVisitor class

Summary

events listener

Demo:

If you want to listen only once:

 visitorInstance.once('ready', () => {
    console.log('Flagship SDK ready !');
  });

If you want to listen anytime:

 visitorInstance.on('saveCache', (args) => {
    const { modifications: { after } } = args;
    console.log('Flagship will save in cache those modifications:\n' + JSON.stringify(after));
  });

FlagshipVisitor contains further event listener which help you to handle the SDK.

If want to listen a listener, here an example:

Event listener Is called multiple times ? Description
ready No This is a mandatory listener to listen. Once it's called, you are ready to use all features from the SDK.
saveCache Yes Called when SDK is about to save in cache fresh modifications. I.e, during first initialization or when using synchronizeModifications().
This listener has an argument in the callback which has following shape:
Key/Property Description
modifications It is an object which contains modifications past and future computed modifications.
Key/Property Description
before Modificaitons previously in cache.
after New modificaitons which are about to be saved in cache.
saveInCacheModifications This is a function you'll have to call if you want to override the modifications which will be saved in the SDK cache.
It has one argument: the modifications name that you want to override.
If you leave it undefined, it will keep default behavior.

updateContext

Demo:

const visitorInstance = sdk.updateContext({
    //...
    some: "NEW_VISITOR_CONTEXT",
    //...
});

edit the context of the visitor

Attribute Type Default Description
context object Required Your Flagship visitor context.

synchronizeModifications

Demo:

visitorInstance.synchronizeModifications().then(
    (statusCode) => console.log(`synchronizeModifications responded with status code:${statusCode}`)
);

Add/update all modifications data which are in cache. Might be useful when your visitor instance has been initialized a while ago and some change have been done on Flagship platform meanwhile. From there some modifications may have changes, so calling synchronizeModifications make sure everything is fine. πŸ˜ƒ

It returns a number (=response status code) when promise is resolved.

Attribute Type Default Description
activate boolean false Trigger activate hit when fetching fresh modifications.

getAllModifications

Demo:

visitorInstance.getAllModifications()
  .then((response) => {
    // do something...
  });

with the following data:

// response.data gives this kind of shape:
{
  visitorId: 'VISITOR_ID',
  campaigns: [
    {
      id: 'CAMPAIGN_ID',
      variationGroupId: 'VARIATION_GROUP_ID',
      variation: {
        id: 'VARIATION_ID',
        modifications: {
          type: 'FLAG',
          value: {
            btnColor: '#fff',
          },
        },
      },
    },
    // {...}
  ]
}

The shape of the object look like same as decision api response, normal mode.

Attribute Type Default Description
activate boolean false To enable your modification(s) while getting them.
NOTE: If modifications already been fetched before, it'll still need to make another request to send the activation.

getModificationsForCampaign

Demo:

visitorInstance.getModificationsForCampaign()
  .then((response) => {
    // do something...
  });

with the following data:

// response.data gives this kind of shape:
{
  visitorId: 'VISITOR_ID',
  campaigns: [
    {
      id: 'CAMPAIGN_ID',
      variationGroupId: 'VARIATION_GROUP_ID',
      variation: {
        id: 'VARIATION_ID',
        modifications: {
          type: 'FLAG',
          value: {
            btnColor: '#fff',
          },
        },
      },
    },
    // {...}
  ]
}

The shape of the object look like same as decision api response.

Attribute Type Default Description
campaignId string Required The id of the campaign from which you want to get modifications.
activate boolean false To enable your modification(s) while getting them.
NOTE: If modifications has already been fetched before, it's still needed to make another request to send the activation.

activateModifications

It will activate the first campaign in cache that’s matching the key set in argument. If conflict exist, you’ll be notified via warning logs (+ debug logs if need details)

Attribute Type Default Description
modificationToActivateRequested Array(object) Required List of all modifications (=key) you're looking to activate. Each element of the array follow this object structure:
Argument Description
key Required. The name of the modification

Demo (with explanations)

Demo:

visitorInstance.activateModifications([
    {
        key: 'btnColor' // required
    },
    {
        key: 'customLabel' // required
    }
]);

The code on the right, will produce the following behaviour:

scenario 1:

Assuming the api gives those informations in the following order:

=> Both campaignA and campaignB will be activated

scenario 2:

Assuming the api gives those informations in the following order:

=> Only campaignA will be activated

scenario 3:

Assuming the api gives those informations in the following order:

=> Both campaignA and campaignB will be activated. But the SDK will logs a conflict for modification customLabel as it is considered as it is not supposed to happen.

getModifications

Demo:

visitorInstance.getModifications([
    {
        key: "btnColor", // required
        defaultValue: "#ff0000", // required
        activate: true // optional
    },
    {
        key: "customLabel", // required
        defaultValue: "Flagship is awesome", // required
    }
], /* ActivateAllModifications */)

will return:

{
  btnColor: '#dcbc02',
  customLabel: 'Flagship is awesome' // default value set (ie: no campaigns have specified this modification)
}

The data returned will be the data from all modifications that you specify in the modificationsRequested argument.

NOTE1: It loads modifications from cache.

NOTE2: You need to fetch modifications to automatically save them in cache. You can achieve it using synchronizeModifications or fetchNow=true.

Attribute Type Default Description
modificationsRequested Array(object) Required List of all modifications you're looking for. Each element of the array follow this object structure:
Argument Description
key Required. The name of the modification.
defaultValue Required. The default value if no value for this modification is found.
activate Optional.
activateAllModifications boolean null If set to true, all modifications will be activated. If set to false, none will be activated.
Be aware that if this argument is set, the attribute activate set in each element of the array modificationsRequested will be ignored.

getModificationInfo

Demo:

visitorInstance.getModificationInfo('myKey');
// will return:
{
  campaignId: 'blntvamqmdvg04g333f0',
  variationGroupId: 'blntcamqmdag04g123h0',
  variationId: 'blntcamqmdag04g331hg',
}
// or: 

null // when nothing found

NOTE1: If the key does not match any campaign, it will return null.

NOTE2: If the key match more than one campaign, it will return informations about the first campaign that the Flagship API returns.

Attribute Type Default Description
key string *required* The key that you want to get modification informations of.

sendHit

Demo:

visitorInstance.sendHit(
  {
    type: 'Screen',
    data: {
        documentLocation: "http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
        pageTitle: "yoloScreen"
  }
).then(() => console.log('Hit send !')

This function allow you to send any kind of hit. All details of each hit below πŸ‘‡.

Attribute Type Default Description
hitShape object (TS: HitShape) Required The HitShape can contain either:
- Transaction hit
- Screen hit
- Item hit
- Event hit
Note: each hit have specific attributes required, click on them to check it.

sendHits

Demo:

visitorInstance.sendHits(
    [
        {
            type: 'Screen',
            data: {
                documentLocation: "http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
                pageTitle: "yoloScreen"
            }
        },
        {
            type: 'Event',
            data: {
                category: 'User Engagement',
                action: 'signOff',
                label: 'Hello world',
                value: 123,
                documentLocation: "http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
                pageTitle: "yoloEvent"
            }
        },
        {
            type: 'Item',
            data: {
                transactionId: '0987654321',
                name: 'yoloItem',
                price: 999,
                code: 'yoloCode',
                category: 'yoloCategory',
                quantity: 123,
                documentLocation: "http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
                pageTitle: "yoloItem"
            }
        },
        {
            type: 'Transaction',
            data: {
                transactionId: '1234567890',
                affiliation: 'yoloAffiliation',
                totalRevenue: 999,
                shippingCost: 888,
                shippingMethod: 'yoloShippingMethod',
                currency: 'yoloCurrency',
                taxes: 1234444,
                paymentMethod:'yoloPaymentMethod',
                itemCount: 2,
                couponCode: 'YOLOCOUPON',
                documentLocation: "http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
                pageTitle: "yoloTransaction"
            }
        },
    ]
).then(() => console.log('All hits send !')

This function allow you to send multiple and any kind of hit. All details of each hit below πŸ‘‡.

Attribute Type Default Description
hitsArray Array(HitShape) Required The HitShape can contain either:
- Transaction hit
- Screen hit
- Item hit
- Event hit
Note: you can mix all of them in the array.
Note 2: each hit have specific attributes required, click on them to check it.

Hits

Summary

Shape of possible hits to send:

Screen Hit

Demo:

visitorInstance.sendHit(
        {
            type: 'Screen',
            data: {
                documentLocation: "http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
                pageTitle: "yoloScreen"
            }
        }
).then(() => console.log('Screen hit send !')
Attribute Type Description
documentLocation string Required. Specifies the current URL of the page, at the moment where the hit has been sent.
pageTitle string Required. Specifies the name of the page, at the moment where the hit has been sent.

Transaction Hit

Demo:

visitorInstance.sendHit(
        {
            type: 'Transaction',
            data: {
                transactionId: '1234567890',
                affiliation: 'yoloAffiliation',
                totalRevenue: 999,
                shippingCost: 888,
                shippingMethod: 'yoloShippingMethod',
                currency: 'yoloCurrency',
                taxes: 1234444,
                paymentMethod:'yoloPaymentMethod',
                itemCount: 2,
                couponCode: 'YOLOCOUPON',
                documentLocation: "http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
                pageTitle: "yoloTransaction"
            }
        }
).then(() => console.log('Transaction hit send !')
Attribute Type Description
transactionId string Required. The id of your transaction.
affiliation string Required. The name of the KPI that you will have inside your reporting.
totalRevenue number Optional. Specifies the total revenue associated with the transaction. This value should include any shipping or tax costs.
shippingCost number Optional. The total shipping cost of your transaction.
shippingMethod string Optional. The shipping method of your transaction.
taxes number Optional. Specifies the total tax of your transaction.
currency string Optional. Specifies the currency of your transaction.
Note: Value should be a valid ISO 4217 currency code.
paymentMethod string Optional. Specifies the payment method used for your transaction.
itemCount number Optional. Specifies the number of item of your transaction.
couponCode string Optional. The coupon code associated with the transaction.
documentLocation string Optional. Specifies the current URL of the page, at the moment where the hit has been sent.
pageTitle string Optional. Specifies the name of the page, at the moment where the hit has been sent.

Item Hit

Demo:

visitorInstance.sendHit(
        {
            type: 'Item',
            data: {
                transactionId: '0987654321',
                name: 'yoloItem',
                price: 999,
                code: 'yoloCode',
                category: 'yoloCategory',
                quantity: 123,
                documentLocation: "http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
                pageTitle: "yoloItem"
            }
        }
).then(() => console.log('Item hit send !')
Attribute Type Description
transactionId string Required. The id of your transaction.
name string Required. The name of your item.
price number Optional. Specifies the price for a single item / unit.
code string Optional. Specifies the SKU or item code.
category string Optional. Specifies the category that the item belongs to.
quantity number Optional. Specifies the number of items purchased.
documentLocation string Optional. Specifies the current URL of the page, at the moment where the hit has been sent.
pageTitle string Optional. Specifies the name of the page, at the moment where the hit has been sent.

Event Hit

Demo:

visitorInstance.sendHit(
        {
            type: 'Event',
            data: {
                category: 'User Engagement',
                action: 'signOff',
                label: 'Hello world',
                value: 123,
                documentLocation: "http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
                pageTitle: "yoloEvent"
            }
        }
).then(() => console.log('Event hit send !')
Attribute Type Description
category string Required. Specifies the category of your event.
Note: The value must be either Action Tracking or User Engagement.
action string Required. The name of the KPI you will have inside the reporting.
label string Optional. Specifies additional description of your event.
value number Optional. Specifies how much you won with that event.
For example, depending on the lead generated, you will earn 10 to 100 euros. Adding that value will enable us to do a sum inside the reporting and give you the average value too.
Note: Value must be non-negative.
documentLocation string Optional. Specifies the current URL of the page, at the moment where the hit has been sent.
pageTitle string Optional. Specifies the name of the page, at the moment where the hit has been sent.

Contributing

Take a look to the Contributors Guide.

What is Flagship ?

Have a look here.

License

Flagship uses license under the Apache version 2.0.