JavaScript, Node, Deno V2.2.X
Introduction
SDK overview
The following documentation will help you get Flagship running in your JavaScript environment (client-side or server-side) with preconfigured methods to implement the Decision API.
Feel free to contact us if you have any questions regarding this documentation.
SDK features
This SDK version helps you:
- Set a visitor ID
- Update user context
- Assign campaigns via the Decision API or via the Bucketing
- Get modifications
- Activate campaigns
- Send hits to our Universal Collect
Prequisites
- Node.js: version 6.0.0 or later
- Npm: version 3.0.0 or later
Good to know
- Latest Version
- Github repository
- Gzipped size:
- SDK runnable on both client-side and server-side
- Typescript code supported
- Open-source demos available using the SDK
Changelog
- Visible on Github
Getting started
Initialization
There are five steps to follow to get started with the JS/NodeJS Flagship SDK:
- Install the node module
npm install @flagship.io/js-sdk
- Import it in your code
import flagship from "@flagship.io/js-sdk"; // ES6 ++
const flagship = require("@flagship.io/js-sdk"); // ES5
- Initialize
const fsInstance = flagship.start("YOUR_ENV_ID", "YOUR_API_KEY", {
/* sdk settings */
});
- Create a visitor
const fsVisitorInstance = fsInstance.newVisitor("YOUR_VISITOR_ID", {
some: "VISITOR_CONTEXT",
});
- When the visitor is
ready
, get modifications
fsVisitorInstance.on("ready", ({ withError, error }) => {
if (withError) {
console.error("Ouch, visitor is ready but with error : " + error.stack);
} else {
console.log("visitor is ready without error ! ✨");
}
const { btnColor, btnText } = fsVisitorInstance.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. 🙂
API Reference
start
function
start
functionTo run experiments with Flagship, you will need to start the SDK. Flagship uses a Flagship
instance that can activate experiments and track events.
Use the following code returns a Flagship
instance:
import flagship from "@flagship.io/js-sdk";
const fsInstance = flagship.start("YOUR_ENV_ID", "YOUR_API_KEY", {
enableConsoleLogs: true,
// other settings...
});
Attribute | Type | Default | Description |
---|---|---|---|
envId | string | Required | Identifies your Flagship account and environment (preprod or prod). Find this ID |
apiKey | string | Required | 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. You can find the api key of your environment on the Flagship dashboard, in Parameters > Environment & Security. |
config | object | defaultConfig | Set up SDK settings. It will override attributes from default configuration so you just need to specify the attributes you need to change. See configuration attributes |
SDK settings
Here are all available settings you can set on the SDK.
Those settings can be setup using start
function.
Below the attributes you can set inside the SDK settings object:
Attribute | Type | Default | Description |
---|---|---|---|
fetchNow | boolean | true | 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. |
enableClientCache | boolean | true | Indicates whether enables or disables the client cache manager. By enabling the client cache, it will allow you to keep cross sessions visitor experience. Note: The client cache is useful only when you do not specify a visitor id when creating a visitor. From there, you only need to be focus on handling the visitor context and whether he is authenticated or not. That's it. Note2: This setting doesn't work and is ignored when SDK is running on server side. |
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 if you need to simulate the API for tests such as end-to-end or if you want to move to an earlier version of the Flagship API. Decision API V1 is set by default but deprecated, starting next version, only Decision API V2 will be implemnented. |
initialModifications | Array(object) | null | This is an object of the data received when fetching the Flagship decision API (decisionMode="API" ). You should specify only the array defined in campaigns attribute from this response.Providing this property 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. |
initialBucketing | Array(object) | null | This is an object of the data received when fetching bucketing endpoint. Providing this prop will make bucketing ready to use and the first polling will immediatly check for an update. If the shape of an element is not correct, an error log will give the reason why. |
decisionMode | 'API' | 'Bucketing' | 'API' | Indicates the behavior of the SDK. In API mode, it will get the modifications using the Flagshipdecision API. With Bucketing , it will load all campaigns onceand compute the variation assignment of the visitor locally. Note: When Bucketing mode is set, you must{" "}specify pollingInterval attribute as well, so that bucketingcan check for updates. Note2: When Bucketing mode is set, and the pollingdetects an update, it won't apply new changes until you manually trigger a campaign synchronization. |
pollingInterval | number | null | Indicates the polling interval period in seconds when SDK is running Bucketing mode ( decisionMode="Bucketing" ).For example, if pollingInterval=5 , a bucketing call will betrigger in background every 5 seconds. Note1: pollingInterval can't be lower than 1 second.Note2: if bucketing is enabled and pollingInterval {" "}value is null , the polling will be done once and an errorlog will be trigger. |
timeout | number | 2 | Indicates the delay in seconds before it triggers a timeout when requesting campaigns via the Flagship decision api. Note: timeout can't be lower than 0 second. |
Flagship
class
Flagship
classnewVisitor
function
newVisitor
functionDemo:
const myVisitorContext = { some: "VISITOR_CONTEXT" };
const fsVisitorInstance = fsInstance.newVisitor("YOUR_VISITOR_ID", {
...myVisitorContext,
});
// OR with auto-gen id
const fsVisitorInstance = fsInstance.newVisitor(null, { ...myVisitorContext });
Be aware that on client side and when you do not specify a visitor id, as
enableClientCache
is enable by default, the SDK will try to find a previous visitor experience. If so, the new visitor will have the same visitor id as it was during the previous visitor session. From there, no id will be automatically generated.
Calling newVisitor
will create and return a FlagshipVisitor
instance.
Following the visitor initialization, you must listen the ready
listener to ensure asynchronous processes inside the SDK are finished.
fsVisitorInstance.on("ready", ({ withError, error }) => {
if (withError) {
console.error("Ouch, visitor is ready but with error : " + error.stack);
} else {
console.log("visitor is ready without error ! ✨");
}
});
newVisitor
function takes the following arguments:
Attribute | Type | Default | Description |
---|---|---|---|
id | string | auto-gen string | Optional. Unique identifier for the current user. This can be an ID from your database or a session ID. If no value is passed, the SDK will automatically generate an unique ID. Learn more |
context | object | {} | Optional. JSON object of key-value pairs describing the user and device context. Learn more |
ready
listener expose in argument an object containing those attributes:
Attribute | Type | Description |
---|---|---|
withError | boolean | Tells if an error occured during the visitor initialization |
error | object | null | Contains the error if occured, null otherwise. |
startBucketingPolling
function
startBucketingPolling
functionDemo:
const fsInstance = flagship.start("ENV_ID", "API_KEY", {
fetchNow: false,
decisionMode: "Bucketing",
pollingInterval: 5 /*, other settings...*/,
});
// do some stuff...
fsInstance.startBucketingPolling();
Start the Bucketing behavior. The Bucketing won't restart if you call this function multiple times.
Return an object with following shape { success: boolean; reason?: string }
.
stopBucketingPolling
function
stopBucketingPolling
functionDemo:
const fsInstance = flagshipSdk.start("ENV_ID", "API_KEY", {
fetchNow: false,
decisionMode: "Bucketing",
pollingInterval: 5 /*, other settings...*/,
});
// do some stuff...
fsInstance.startBucketingPolling(); // start manually the bucketing (as fetchNow is equal to "false")
setTimeout(() => fsInstance.stopBucketingPolling(), 100 * 1000); // stop bucketing 100 seconds later...
Stop the Bucketing behavior. If you call this function multiple times, you will see a log notifying that it's already stopped.
Return an object with following shape { success: boolean; reason?: string }
.
FlagshipVisitor
class
FlagshipVisitor
class- Event listeners
- updateContext
- synchronizeModifications
- getModifications
- getAllModifications
- getModificationsForCampaign
- getModificationInfo
- activateModifications
- sendHit
- sendHits
- authenticate
- unauthenticate
Event listeners
The FlagshipVisitor
includes event listeners to help you handle the SDK.
To listen once:
fsVisitorInstance.once("ready", () => {
console.log("Flagship SDK is ready!");
});
To listen anytime:
fsVisitorInstance.on("saveCache", (args) => {
const {
modifications: { after },
} = args;
console.log(
"Flagship SDK will save in cache those modifications:\n" +
JSON.stringify(after)
);
});
Event listener | 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(). |
The saveCache
listener has an argument in the callback with the following shape:
Key/Property | Description |
---|---|
modifications | Object containing modifications. Set value to before for modifications that were previously in cache and after for new modificaitons that are about to be saved in cache |
saveInCacheModifications | Call this function if you want to override the modifications saved in the SDK cache. Its only argument is the name of the modification that you wish to override. Leaving it undefined keeps the default behavior. |
Before using any function from
FlagshipVisitor
, it is important that you have listened theready
event to ensure everything is working properly and your visitor is up to date with campaigns assignment.
updateContext
function
updateContext
functionThe visitor context is a property dataset which defines the current user of your app. This dataset is used as targeting criteria for campaign assignment.
Use the updateContext
function to modify the value of existing attributes or add new attributes entirely:
const fsVisitorInstance = fsInstance.updateContext({
//...
some: "NEW_VISITOR_CONTEXT",
//...
});
The function takes the following arguments:
Attribute | Type | Default | Description |
---|---|---|---|
context | object | {} | JSON object of key-value pairs describing the user and device context. Learn more |
Updating the context does not automatically activate campaigns matching this new context. To do so, you must manually call the
synchronizeModifications
function.
synchronizeModifications
function
synchronizeModifications
functionThe synchronizeModifications
function updates campaigns targeting that match the current visitor context.
When in decisionMode="API"
, it will also refreshes all modification data in cache by making a new call to the Flagship decision API.
It returns a Promise<number>
where number
is the response status code when the promise is resolved.
The function takes the following arguments:
Attribute | Type | Default | Description |
---|---|---|---|
activate | boolean | false | Triggers activate hit when retrieving fresh modifications. |
getModifications
function
getModifications
functionThe getModifications
function returns the data from all modifications that you specify in the modificationsRequested
argument.
Attribute | Type | Default | Description |
---|---|---|---|
modificationsRequested | Array(object) | Required | List of all modifications you're looking for. See object structure below. |
activateAllModifications | boolean | null | If set to true , all modifications will be activated. If set to false , none will be activated. NOTE: Setting this argument will override the activate attribute set in each element of the modificationsRequested array. |
Each element of the modificationsRequested
array argument follows this object structure:
Argument | Default | Description |
---|---|---|
key | Required | The name of the modification. |
defaultValue | Required | The default value if no value for this modification is found. |
activate | Optional | Determines whether or not the modification is activated (if activateAllModifications is not set). |
This method loads modifications from cache. To save modifications automatically in cache, you need to retrieve them using
synchronizeModifications
orfetchNow=true
.If the cache is empty,
getModifications
function will always return default values.
getAllModifications
function
getAllModifications
functionThe getAllModifications
method returns a Promise<object>
containing all the data for all the campaigns associated with the current visitor.
The object resolved by the promise has the same shape as the Decision API response (normal mode).
The function takes the following arguments:
Attribute | Type | Default | Description |
---|---|---|---|
activate | boolean | false | Enables modifications while getting them. NOTE: If modifications have already been retrieved, the activation will be sent in another request. |
getModificationsForCampaign
function
getModificationsForCampaign
functionUseful to request the data for a specific campaign.
The function takes the following arguments:
Attribute | Type | Default | Description |
---|---|---|---|
campaignId | string | Required | Identifies the campaign whose modifications you want to retrieve. **See description |
activate | boolean | false | Enables modifications while getting them. NOTE: If modifications have already been retrieved, the activation will be sent in another request. |
getModificationInfo
function
getModificationInfo
functionUsing the getModificationInfo
function allows you to specify a key in the argument. It returns an object
with information about the modification that matches the specified key.
fsVisitorInstance
.getModificationInfo("myKey")
.then((response) => {
// do some stuff...
})
.catch((error) => {
// something is going wrong...
});
The example above returns a Promise<object | null>
. (Typescript: GetModificationInfoOutput)
The response can either be null
(when the modification does not exist) or either be an object
with following shape:
{
campaignId: 'CAMPAIGN_ID',
variationGroupId: 'VARIATION_GROUP_ID',
variationId: 'VARIATION_ID',
}
The function takes the following arguments:
Attribute | Type | Default | Description |
---|---|---|---|
key | string | Required | The key that you want to get modification informations of. |
If the key matches more than one campaign, it will return information for the first campaign that the Flagship SDK has in its campaigns cache.
activateModifications
function
activateModifications
functionIt activates the first campaign in cache that matches the key specified in the argument.
This function returns nothing and takes following argument:
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 | Default | Description |
---|---|---|
key | Required | String. Name of the modification |
In case of any conflicts, you'll be notified via
warning
logs (ordebug
logs if you need more details).
sendHit
function
sendHit
functionDemo:
fsVisitorInstance.sendHit(
{
type: 'Screen',
data: {
documentLocation: "http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
pageTitle: "testScreen"
}
).then(() => console.log('Hit send !')
The sendHit
function lets you to send any type of hit.
Returns a Promise<void>
and has following argument:
Attribute | Type | Default | Description |
---|---|---|---|
hitShape | object (TS: HitShape) | Required | The hitShape object can contain aTransaction, Screen, Item, or Event hit. Note: click on the hit name to see the specific attributes each type requires. |
sendHits
function
sendHits
functionDemo:
fsVisitorInstance.sendHits(
[
{
type: 'Screen',
data: {
documentLocation: "http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
pageTitle: "testScreen"
}
},
{
type: 'Event',
data: {
category: 'User Engagement',
action: 'signOff',
label: 'Hello world',
value: 123,
documentLocation: "http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
pageTitle: "testEvent"
}
},
{
type: 'Item',
data: {
transactionId: '0987654321',
name: 'testItem',
price: 999,
code: 'testCode',
category: 'testCategory',
quantity: 123,
documentLocation: "http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
pageTitle: "testItem"
}
},
{
type: 'Transaction',
data: {
transactionId: '1234567890',
affiliation: 'testAffiliation',
totalRevenue: 999,
shippingCost: 888,
shippingMethod: "DHL",
currency: "USD",
taxes: 1234444,
paymentMethod: "creditCard",
itemCount: 2,
couponCode: 'TESTCOUPON',
documentLocation: "http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
pageTitle: "testTransaction"
}
},
]
).then(() => console.log('All hits send !')
The sendHits
function allow you to send multiple hits of any type in a single request:
Returns a Promise<void>
and has following argument:
Attribute | Type | Default | Description |
---|---|---|---|
hitsArray | Array(HitShape) | Required | The hitShape object can contain aTransaction, Screen, Item, or Event hit. Note: click on the hit name to see the specific attributes each type requires. |
authenticate
function
authenticate
functionTells the SDK that the visitor is switching from an anonymous to an authenticate state by changing its visitor id and ensure that it's keeping the same experience (= same modifications).
This function returns a Promise<void>
(asynchronous behavior) and takes following argument:
Attribute | Type | Default | Description |
---|---|---|---|
id | string | Required | A visitor id which will be the new id assigned to this visitor. |
unauthenticate
function
unauthenticate
functionTells the SDK that the visitor is switching from an authenticate to an anonymous state. Under the hood, it will set back the initial id (anonymous) that was set during visitor initialization and this will ensure that it's keeping the same experience (= same modifications).
This function returns a Promise<void>
(asynchronous behavior) and doesn't have any argument.
unauthenticate
function will return an error if you didn't calledauthenticate
function before.
Getting modifications
with getModifications
Click here for details on getModifications
const getModificationsOutput = fsVisitorInstance.getModifications(
[
{
key: "btnColor", // required
defaultValue: "#ff0000", // required
activate: true, // optional ("false" by default)
},
{
key: "customLabel", // required
defaultValue: "Flagship is awesome", // required
},
] /* ActivateAllModifications */
);
From there, getModificationsOutput
will have:
// Note that for each modification key, the value depends on if your visitor is matching corresponding campaign or not.
{
btnColor: '#dcbc02',
customLabel: 'Flagship is awesome' // default value set (ie: no campaigns have specified this modification)
}
with getAllModifications
Click here for details on getAllModifications
fsVisitorInstance.getAllModifications().then((response) => {
// Do something
});
The response includes the following data:
{
visitorId: 'VISITOR_ID',
campaigns: [
{
id: 'CAMPAIGN_ID',
variationGroupId: 'VARIATION_GROUP_ID',
variation: {
id: 'VARIATION_ID',
modifications: {
type: 'FLAG',
value: {
'MODIFICATION_KEY': 'MODIFICATION_VALUE',
},
},
},
},
// {...}
]
}
with getModificationsForCampaign
Click here for details on getModificationsForCampaign
fsVisitorInstance.getModificationsForCampaign().then((response) => {
// Do something
});
The response includes the following data:
{
visitorId: 'VISITOR_ID',
campaigns: [
{
id: 'CAMPAIGN_ID',
variationGroupId: 'VARIATION_GROUP_ID',
variation: {
id: 'VARIATION_ID',
modifications: {
type: 'FLAG',
value: {
'MODIFICATION_KEY': 'MODIFICATION_VALUE',
},
},
},
},
// {...}
]
}
Campaign synchronization
with synchronizeModifications
Click here for details on synchronizeModifications
fsVisitorInstance
.synchronizeModifications()
.then((statusCode) =>
console.log(
`synchronizeModifications responded with status code:${statusCode}`
)
);
Campaign activation
Campaign activation tells Flagship Decision API that modifications have been applied to your visitor.
with activateModifications
Click here for details on activateModifications
fsVisitorInstance.activateModifications([
{
key: "btnColor", // required
},
{
key: "customLabel", // required
},
]);
The code above will yield one of the following behaviors:
-
Scenario 1
Assuming the Decision API returns the campaign information in the following order:
- Modification
btnColor
is in campaign campaignA - Modification
customLabel
is in campaign campaignB
Both campaignA and campaignB will be activated
- Modification
-
Scenario 2
Assuming the Decision API returns the campaign information in the following order:
- Modification
btnColor
and customLabel is in campaign campaignA - Modification
customLabel
is in campaign campaignB
Only campaignA will be activated
- Modification
-
Scenario 3
Assuming the Decision API returns the campaign information in the following order:
- Modification
customLabel
is in campaign campaignA - Modification
btnColor
andcustomLabel
is in campaign campaignB
Both campaignA and campaignB will be activated, but the SDK will log a conflict for the
customLabel
modification considering this scenario is not supposed to happen. - Modification
Experience continuity
It might happen that a visitor from your app is not yet recognized and is being authenticated (and recognized) later on...
From there, we provide the ability to ensure that during such transition, your visitor will keep the same experience (meaning targetting still the same campaign's variations and thus the same modifications).
In order to do a successful experience continuity, we will have to distinguish when the visitor is anonymous or authenticated.
Let's assume basic scenario to understand how things work:
- Your visitor arrives on your app for the first time.
We need to initialize the visitor but as we don't known anything about this visitor, we'll create a random visitor id or let the SDK do it for us. You can also specify some visitor context if necessary.
visitorInstance = sdk.newVisitor(null, { ...someVisitorContext });
visitorInstance.on("ready", () => {
console.log("visitor with new experience is ready ! ✨");
});
We put null
in the first argument so the SDK has auto-created an id for our visitor.
Whatever how it has been set, the actual visitor id will be what we call its anonymous id.
- Your visitor is signing in.
To tell the SDK about this change, you'll have to call authenticate
function which takes a visitor id as argument.
The visitor id set in argument is required and should be an existing visitor id (that has previously seen specific campaign's modifications) in order to make the experience continuity effective.
await visitorInstance.authenticate("VISITOR_ID_ALREADY_KNOWN_BY_FLAGSHIP");
// OR
visitorInstance
.authenticate("VISITOR_ID_ALREADY_KNOWN_BY_FLAGSHIP")
.then(() => console.log("visitor successfully updated."));
This new visitor id is what we call its authenticated id.
The visitor is updated as authenticated, keeping the previous variations from campaigns that are still matched and thus gives you same modifications as before being logged in.
Keep in mind that if the visitor also has its context changed, you might still have changes on modifications as your visitor might target new campaigns.
- Your visitor decide to sign out.
If you want to keep the same visitor experience, then you should do:
await visitorInstance.unauthenticate();
// OR
visitorInstance
.unauthenticate()
.then(() => console.log("visitor successfully updated."));
If for some reason you decide to deliver a new visitor experience, you should create a new visitor instead:
const newVisitorInstance = fsInstance.newVisitor(null, {
...someVisitorContext,
});
fsVisitorInstance.on("ready", () => {
console.log("visitor with new experience is ready ! ✨");
});
Hit tracking
This section helps you track your users in your application and learn how to build hits in order to feed campaign goals. For more information about our measurement protocol, read our Universal Collect documentation.
There are four different types of hits available:
Screen
Demo:
fsVisitorInstance.sendHit(
{
type: 'Screen',
data: {
documentLocation: "Home page",
}
}
).then(() => console.log('Screen hit send !')
Attribute | Type | Description |
---|---|---|
documentLocation | string | Required. Specifies the current name of the screen when the hit is sent. |
Page
Demo:
fsVisitorInstance.sendHit(
{
type: 'Page',
data: {
documentLocation: "http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
}
}
).then(() => console.log('Page hit send !')
Attribute | Type | Description |
---|---|---|
documentLocation | string | Required. Specifies the current URL of the page when the hit is sent. |
Transaction
Demo:
fsVisitorInstance.sendHit(
{
type: 'Transaction',
data: {
transactionId: '1234567890',
affiliation: 'testAffiliation',
totalRevenue: 999,
shippingCost: 888,
shippingMethod: "DHL",
currency: "USD",
taxes: 1234444,
paymentMethod: "creditCard",
itemCount: 2,
couponCode: 'TESTCOUPON',
documentLocation: "http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
pageTitle: "testTransaction"
}
}
).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. Learn more |
totalRevenue | number | Optional. Specifies the total revenue associated with the transaction. This value should include any shipping and/or tax amounts. |
shippingCost | number | Optional. The total shipping cost of your transaction. |
shippingMethod | string | Optional. The shipping method for your transaction. |
taxes | number | Optional. Specifies the total amount of taxes in your transaction. |
currency | string | Optional. Specifies the currency of your transaction. NOTE: This 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 items of your transaction. |
couponCode | string | Optional. The coupon code associated with the transaction. |
documentLocation | string | Optional. Specifies the current URL of the page when the hit is sent. |
pageTitle | string | Optional. Specifies the current name of the page when the hit is sent. |
Item
Demo:
fsVisitorInstance.sendHit(
{
type: 'Item',
data: {
transactionId: '0987654321',
name: 'testItem',
price: 999,
code: 'testCode',
category: 'testCategory',
quantity: 123,
documentLocation: "http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
pageTitle: "testItem"
}
}
).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 when the hit is sent. |
pageTitle | string | Optional. Specifies the current name of the page when the hit is sent. |
The
ITEM
hit isn't available yet in the Flagship reporting view.
Event
Demo:
fsVisitorInstance.sendHit(
{
type: 'Event',
data: {
category: 'User Engagement',
action: 'signOff',
label: 'Hello world',
value: 123,
documentLocation: "http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
pageTitle: "testEvent"
}
}
).then(() => console.log('Event hit send !')
Attribute | Type | Description |
---|---|---|
category | string | Required. Specifies the category of your event. NOTE: This 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 the monetary value associated with an event (e.g. you earn 10 to 100 euros depending on the quality of lead generated). NOTE: this 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. |
Demos
Code sandbox using Express JS
Node JS using Express JS
[Deprecated] React app
Appendix
Release note
Take a look to the Release note.
Contributing
Take a look at the Contributors Guide if you're interested in contributing to the SDK.
License
This Flagship SDK is distributed under the Apache version 2.0 license.
Updated 5 months ago