Package Exports
- @flagship.io/js-sdk
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@flagship.io/js-sdk) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme

Flagship - JS SDK
Prerequisites
Node.js: version 6.0.0 or later...
Npm: version 3.0.0 or later...
Good to know
-
- Typescript supported β
-
- Light weight SDK π (Gzipped size=38KB~)
-
- How to use the SDK in practice β :
-
- Release notes available to stay in touch π
Getting Started
- Install the node module:
npm install @flagship.io/js-sdk- Then import it in your code :
import flagship from "@flagship.io/js-sdk"; // ES6 ++
const flagship = require("@flagship.io/js-sdk"); // ES5- Then initialize:
const sdk = flagship.initSdk("YOUR_ENV_ID", { /* sdk settings */ });- Then create a visitor:
const visitorInstance = sdk.newVisitor("YOUR_VISITOR_ID",{
//...
some: "VISITOR_CONTEXT",
//...
});
visitorInstance.on('ready', () => {
console.log('visitorInstance is ready ! β¨')
});- Then get modifications:
visitorInstance.getModifications([{key: "btnColor", defaultValue: "#ff0000"}, {key: "btnText", defaultValue: "Wahoo !"}])
.then(({btnColor, btnText}) => {
// do some stuff
myButton.setColor(btnColor);
myButton.setText(btnText);
})- Or even better, if you fetched campaigns already before (during initialization as example):
const {btnColor, btnText} = visitorInstance.getModificationsCache([{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. π
SDK Settings
This is all available settings which you can set on the SDK.
Those settings can be setup using initSdk function (sample inside).
Here are the attributes which 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 only display logs such as Warnings, Errors, Fatal errors and Info |
| logPathName | String | 'flagshipNodeSdkLogs' | This is the path where logs will be written when SDK is running. By default it will create a folder named flagshipNodeSdkLogs at the root of your project |
| nodeEnv | String | 'production' | If value is other than production, it will also display Debug logs |
JS SDK Features
Don't hesitate to have a look to the main Flagship technical doc as well π.
flagshipSdk object
Flagship class
FlagshipVisitor class
- setContext
- synchronizeModifications
- getAllModifications
- getModificationsForCampaign
- getModifications
- activateModifications
- getModificationsCache
- sendHits
Shape of possible hits to send
flagshipSdk object
initSdk
return a
Flagshipinstance.
| 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 attributes which you need to change. You can check config attributes here |
Demo:
const sdk = flagship.initSdk("YOUR_ENV_ID",
{
enableConsoleLogs: true,
fetchNow: false,
});Flagship class
newVisitor
return a FlagshipVisitor instance.
| argument | type | default | description |
|---|---|---|---|
| id | String | *required* | Your Flagship visitor id |
| context | Object | *required* | Your Flagship visitor context |
Demo:
const visitorInstance = sdk.newVisitor("YOUR_VISITOR_ID",{
//...
some: "VISITOR_CONTEXT",
//...
});
visitorInstance.on('ready', () => {
console.log('visitorInstance is ready ! β¨')
});FlagshipVisitor class
- setContext
- synchronizeModifications
- getAllModifications
- getModificationsForCampaign
- getModifications
- getModificationsCache
- sendHits
setContext
edit the context of the visitor
return nothing
| argument | type | default | description |
|---|---|---|---|
| context | Object | *required* | Your Flagship visitor context |
Demo:
const visitorInstance = sdk.setContext({
//...
some: "NEW_VISITOR_CONTEXT",
//...
});synchronizeModifications
return a
Promise<number>
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.
| argument | type | default | description |
|---|---|---|---|
| activate | Boolean | false | Trigger activate hit when fetching fresh modifications. |
Demo:
visitorInstance.synchronizeModifications().then(
(statusCode) => console.log(`synchronizeModifications responded with status code:${statusCode}`)
);getAllModifications
return an
Promise<object>which contains all data for all campaigns which the visitor can have
The shape of the object look like same as decision api response, normal mode.
| argument | 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 |
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',
},
},
},
},
// {...}
]
}getModificationsForCampaign
return a
promise<object>which contains the data for a specific campaign
The shape of the object look like same as decision api response.
| argument | 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 already been fetched before, it'll still need to make another request to send the activation |
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',
},
},
},
},
// {...}
]
}getModifications
return a
Promise<object>where each key is a modification with corresponding value
The data returned will be the data from all modifications that you specify in the modificationsRequested argument
| argument | type | default | description | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| modificationsRequested | Array(Object) | *required* | List of all modifications you're looking for. Each element of the array follow this object structure:
|
||||||||
| 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 array modificationsRequested will be ignored. |
Demo:
visitorInstance.getModifications([
{
key: "btnColor", // required
defaultValue: "#ff0000", // required
activate: true // optional
},
{
key: "customLabel", // required
defaultValue: "Flagship is awesome", // required
}
], /* ActivateAllModifications */)
.then(({btnColor, customLabel}) => {
// do some stuff
})
.catch((error) => {
// error :(
})will return:
// modifications shape:
{
btnColor: '#dcbc02',
customLabel: 'Flagship is awesome' // default value set (ie: no campaigns have specified this modification)
}activateModifications
return
nothing(for the moment...)
Kind of same behavior as getModifications. 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)
| argument | 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:
|
Demo:
visitorInstance.activateModifications([
{
key: "btnColor", // required
},
{
key: "customLabel", // required
}
])will produce following behaviour:
scenario 1:
Assuming the api gives those informations in the following order:
- modification btnColor is in campaign campaignA
- modification customLabel is in campaign campaignB
=> Both campaignA and campaignB will be activated
scenario 2:
Assuming the api gives those informations in the following order:
- modification btnColor and customLabel is in campaign campaignA
- modification customLabel is in campaign campaignB
=> Only campaignA will be activated
scenario 3:
Assuming the api gives those informations in the following order:
- modification customLabel is in campaign campaignA
- modification btnColor and customLabel is in campaign campaignB
=> 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.
getModificationsCache
return an
objectwhere each key is a modification with corresponding value
Same behavior as getModifications function but without returning a promise.
NOTE: You need to fetch modifications to automatically save them in cache. You can achieve it using synchronizeModifications or fetchNow=true.
| argument | type | default | description | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| modificationsRequested | Array(Object) | *required* | List of all modifications you're looking for. Each element of the array follow this object structure:
|
||||||||
| 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 array modificationsRequested will be ignored. |
Demo:
visitorInstance.getModificationsCache([
{
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)
}sendHits
return a
Promise<void>
This function allow you to send any kind of hit. All details of each hit below π.
| argument | 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. NOTE2: each hit have specific attributes required, click on them to check it. |
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 !')Shape of possible hits to send
Transaction Hit
| 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. |
Screen Hit
| 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. |
Item Hit
| 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
| 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.