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:

Prequisites

  • Node.js: version 6.0.0 or later
  • Npm: version 3.0.0 or later

Good to know

Changelog

Getting started

Initialization

There are five steps to follow to get started with the JS/NodeJS Flagship SDK:

  1. Install the node module
npm install @flagship.io/js-sdk
  1. Import it in your code
import flagship from "@flagship.io/js-sdk"; // ES6 ++

const flagship = require("@flagship.io/js-sdk"); // ES5
  1. Initialize
const fsInstance = flagship.start("YOUR_ENV_ID", "YOUR_API_KEY", {
  /* sdk settings */
});
  1. Create a visitor
const fsVisitorInstance = fsInstance.newVisitor("YOUR_VISITOR_ID", {
  some: "VISITOR_CONTEXT",
});
  1. 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

To 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...
});
AttributeTypeDefaultDescription
envIdstringRequiredIdentifies your Flagship account and environment (preprod or prod). Find this ID
apiKeystringRequiredIf 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.
configobjectdefaultConfigSet 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:

AttributeTypeDefaultDescription
fetchNowbooleantrueDecide to fetch automatically modifications data when creating a new FlagshipVisitor.
activateNowbooleanfalseDecide to trigger automatically the data when creating a new
FlagshipVisitor.

Note: when set to true, it will implicitly set fetchNow=true as well.
enableConsoleLogsbooleanfalseEnable it to display logs on the console when SDK is running. This will display logs such as Warnings, Errors, Fatal errors and Info.
enableClientCachebooleantrueIndicates 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.
nodeEnvstring'production'If value is other than production, it will also display Debug logs.
flagshipApistring'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.
initialModificationsArray(object)nullThis 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.
initialBucketingArray(object)nullThis 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 Flagship
decision API. With Bucketing, it will load all campaigns once
and compute the variation assignment of the visitor locally.

Note: When Bucketing mode is set, you must{" "}
specify pollingInterval attribute as well, so that bucketing
can check for updates.

Note2: When Bucketing mode is set, and the polling
detects an update, it won't apply new changes until you manually trigger a
campaign synchronization.
pollingIntervalnumbernullIndicates the polling interval period in seconds when SDK is running
Bucketing mode (decisionMode="Bucketing").

For example, if pollingInterval=5, a bucketing call will be
trigger 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 error
log will be trigger.
timeoutnumber2Indicates 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

newVisitor function

Demo:

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:

AttributeTypeDefaultDescription
idstringauto-gen stringOptional. 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
contextobject{}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:

AttributeTypeDescription
withErrorbooleanTells if an error occured during the visitor initialization
errorobject | nullContains the error if occured, null otherwise.

startBucketingPolling function

Demo:

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

Demo:

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

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 listenerCalled multiple times?Description
readynoThis is a mandatory listener to listen. Once it's called, you are ready to use all features from the SDK.
saveCacheyesCalled 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/PropertyDescription
modificationsObject 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
saveInCacheModificationsCall 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 the ready event to ensure everything is working properly and your visitor is up to date with campaigns assignment.

updateContext function

The 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:

AttributeTypeDefaultDescription
contextobject{}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

See the demo

The 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:

AttributeTypeDefaultDescription
activatebooleanfalseTriggers activate hit when retrieving fresh modifications.

getModifications function

See the demo

The getModifications function returns the data from all modifications that you specify in the modificationsRequested argument.

AttributeTypeDefaultDescription
modificationsRequestedArray(object)RequiredList of all modifications you're looking for. See object structure below.
activateAllModificationsbooleannullIf 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:

ArgumentDefaultDescription
keyRequiredThe name of the modification.
defaultValueRequiredThe default value if no value for this modification is found.
activateOptionalDetermines 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 or fetchNow=true.

If the cache is empty, getModifications function will always return default values.

getAllModifications function

See the demo

The 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:

AttributeTypeDefaultDescription
activatebooleanfalseEnables modifications while getting them. NOTE: If modifications have already been retrieved, the activation will be sent in another request.

getModificationsForCampaign function

See the demo

Useful to request the data for a specific campaign.

The function takes the following arguments:

AttributeTypeDefaultDescription
campaignIdstringRequiredIdentifies the campaign whose modifications you want to retrieve. **See description
activatebooleanfalseEnables modifications while getting them. NOTE: If modifications have already been retrieved, the activation will be sent in another request.

getModificationInfo function

Using 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:

AttributeTypeDefaultDescription
keystringRequiredThe 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

See the demo

It activates the first campaign in cache that matches the key specified in the argument.

This function returns nothing and takes following argument:

AttributeTypeDefaultDescription
modificationToActivateRequestedArray(object)RequiredList of all modifications (=key) you're looking to activate.

Each element of the array follow this object structure:

ArgumentDefaultDescription
keyRequiredString. Name of the modification

📘

In case of any conflicts, you'll be notified via warning logs (or debug logs if you need more details).

sendHit function

Demo:

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:

AttributeTypeDefaultDescription
hitShapeobject (TS: HitShape)RequiredThe hitShape object can contain a
Transaction, Screen, Item, or Event hit.

Note: click on the hit name to see the specific attributes each
type requires.

sendHits function

Demo:

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:

AttributeTypeDefaultDescription
hitsArrayArray(HitShape)RequiredThe hitShape object can contain a
Transaction, Screen,
Item, or Event hit.

Note: click on the hit name to see the specific attributes each type requires.

authenticate function

See the demo

Tells 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:

AttributeTypeDefaultDescription
idstringRequiredA visitor id which will be the new id assigned to this visitor.

unauthenticate function

See the demo

Tells 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 called authenticate 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

  • 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

  • Scenario 3

    Assuming the Decision API returns the campaign information 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 log a conflict for the customLabel modification considering this scenario is not supposed to happen.

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:

  1. 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.

  1. 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.

  1. 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 !')
AttributeTypeDescription
documentLocationstringRequired. 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 !')
AttributeTypeDescription
documentLocationstringRequired. 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 !')
AttributeTypeDescription
transactionIdstringRequired. The ID of your transaction.
affiliationstringRequired. The name of the KPI that you will have inside your reporting. Learn more
totalRevenuenumberOptional. Specifies the total revenue associated with the transaction. This value should include any shipping and/or tax amounts.
shippingCostnumberOptional. The total shipping cost of your transaction.
shippingMethodstringOptional. The shipping method for your transaction.
taxesnumberOptional. Specifies the total amount of taxes in your transaction.
currencystringOptional. Specifies the currency of your transaction. NOTE: This value should be a valid ISO 4217 currency code.
paymentMethodstringOptional. Specifies the payment method used for your transaction.
itemCountnumberOptional. Specifies the number of items of your transaction.
couponCodestringOptional. The coupon code associated with the transaction.
documentLocationstringOptional. Specifies the current URL of the page when the hit is sent.
pageTitlestringOptional. 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 !')
AttributeTypeDescription
transactionIdstringRequired. The ID of your transaction.
namestringRequired. The name of your item.
pricenumberOptional. Specifies the price for a single item/unit.
codestringOptional. Specifies the SKU or item code.
categorystringOptional. Specifies the category that the item belongs to.
quantitynumberOptional. Specifies the number of items purchased.
documentLocationstringOptional. Specifies the current URL of the page when the hit is sent.
pageTitlestringOptional. 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 !')
AttributeTypeDescription
categorystringRequired. Specifies the category of your event. NOTE: This value must be either 'Action Tracking' or 'User Engagement'.
actionstringRequired. The name of the KPI you will have inside the reporting.
labelstringOptional. Specifies additional description of your event.
valuenumberOptional. 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.
documentLocationstringOptional. Specifies the current URL of the page, at the moment where the hit has been sent.
pageTitlestringOptional. Specifies the name of the page, at the moment where the hit has been sent.

Demos

Code sandbox using Express JS

Live Demo 🕹

Node JS using Express JS

Readme 📖

[Deprecated] React app

react-deprecated-demo

Readme 📖

Live Demo 🕹

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.