Flagship class

The Flagship class represents the SDK. It facilitates the initialization process and creation of new visitors.

start method

Starts the flagship SDK and returns the Flagship instance.

  • static start (envId: string, apiKey: string, config?: IFlagshipConfig): Flagship

Arguments:

NameTypeRequiredDescription
envIdStringRequiredEnvironment id provided by Flagship.
apiKeyStringRequiredApi authentication key provided by Flagship.
configObjectOptionalCustom flagship configuration. see SDK configuration

Example:

import { Flagship } from "@flagship.io/js-sdk";

Flagship.start("<ENV_ID>", "<API_KEY>");

// or

const fsInstance = Flagship.start("<ENV_ID>", "<API_KEY>");
import { Flagship } from "https://deno.land/x/flagship_io_js_sdk/mod.ts";

Flagship.start("<ENV_ID>", "<API_KEY>");

// or

const fsInstance = Flagship.start("<ENV_ID>", "<API_KEY>");

newVisitor method

Creates and returns a new Visitor instance

This method should always be called after the Flagship SDK has started.

  • static newVisitor (params: INewVisitor): Visitor

  • newVisitor (params: INewVisitor): Visitor

This method accepts only one argument with the following shape:

KeyTypeDefaultDescription
visitorIdstringundefinedOptional
Unique visitor identifier.
Note:

- If not set, it will be generated automatically.
- In client-side, if not specified, the id will either be automatically generated or will be the visitor id from the previous session (if reuseVisitorIds is set to true).
hasConsentedbooleanfalseRequired
Specifies if the visitor has consented for personal data usage.
When set to false, some features will be deactivated and the cache will be deactivated and cleared.
isAuthenticatedbooleanfalseSpecify if the visitor is authenticated or anonymous for Experience continuity.
contextobject { [key: string]: string | number | boolean }{}The visitor context is a dataset key/value that defines the current visitor. It is sent to Flagship for targeting purposes (use-case assignment) and to enrich reporting with Context Filters.
Note:Context keys must be strings, and the value types must be one of the following: number, boolean, or string.
shouldSaveInstancebooleanfalse on server-side
true on client-side
Specifies whether the newly created visitor instance should be saved into Flagship instance.
If set to true, the newly created visitor instance will be saved into Flagship.
If set to false, the newly created visitor instance will not be saved, but simply returned.
initialCampaignsobjectundefinedOptional
An object containing the data received when fetching the Flagship decision API (decisionMode="API").
Providing this property avoids the SDK from having an empty cache during first initialization.
initialFlagsDataarrayundefinedOptional
A set of flag data provided to avoid the SDK from having an empty cache during the first initialization.
onFetchFlagsStatusChangedfunction(object):voidundefinedOptional
Callback function that will be called when the fetch flags status changes.
see arguments

πŸ“˜

Information

  • When the property fetchNow in the configuration is set to true, the SDK will automatically fetch flag right after finishing creating the visitor.
  • Visitor context keys must have a type of string
  • Visitor context values must have a type of string, boolean, number
  • Visitor context keys and values are case sensitive
  • When both initialCampaigns and initialFlags are provided, the system will disregard initialCampaigns and only use initialFlags.

onFetchFlagsStatusChanged

The onFetchFlagsStatusChanged function has one argument

ArgumentTypeDescription
statusnumberStatus of the SDK. seeFetchFlagsStatus

FetchFlagsStatus object

FetchFlagsStatus is an object representing the status of visitor fetch for flag data.

type FetchFlagsStatus = {
  /**
   * The new status of the flags fetch.
   */
  status: FSFetchStatus;
  /**
   * The reason for fetching Flags.
   */
  reason: FSFetchReasons;
};
Key/PropertyTypeDescription
statusobjectEnum representing the status of the flags in the Flagship SDK.
reasonobjectEnum representing the reasons for fetching Flags.

FSFetchStatus enum

FSFetchStatus is an enum representing the status of the flags in the visitor instance

KeyTypeDescription
FETCHEDstringThe flags have been successfully fetched from the API or re-evaluated in bucketing mode.
FETCH_REQUIREDstringThe flags need to be re-fetched due to a change in context, or because the flags were loaded from cache or XPC.
NOT_FOUNDstringThe flag was not found or does not exist.
PANICstringThe SDK is in PANIC mode: All features are disabled except for the one to fetch flags.

FSFetchReasons enum

FSFetchReasons is an enum representing the reasons for re-fetching Flags.

KeyTypeDescription
AUTHENTICATEstringIndicates that the XPC method 'authenticate' has been called.
FETCH_ERRORstringIndicates that fetching flags has failed.
NONEstringIndicates that there is no specific reason for fetching flags.
READ_FROM_CACHEstringIndicates that flags have been fetched from the cache.
UPDATE_CONTEXTstringIndicates that a context has been updated or changed.
UNAUTHENTICATEstringIndicates that the XPC method 'unauthenticate' has been called.
VISITOR_CREATEDstringIndicates that the visitor has been created.

getStatus method

Returns current status of Flagship SDK. seeFSSdkStatus

  • getStatus (): FSSdkStatus
  • static getStatus (): FSSdkStatus

getConfig method

Returns the current config used by the SDK. see configuration attribute

  • getConfig (): IFlagshipConfig
  • static getConfig (): IFlagshipConfig

getVisitor method

Returns the last visitor created and saved or return undefined if no visitor has been saved. see newVisitor.

  • getVisitor ():Visitor|undefined
  • static getVisitor ():Visitor|undefined

close method

This method batches and sends all collected hits. It should be called when your application (script) is about to terminate or in the event of a crash to ensures that all collected data is sent and not lost.

  • close ():Promise<void>
  • static close ():Promise<void>

SDK configuration

Below the details of every attribute you can set inside the SDK config object :

AttributeTypeDefaultDescription
decisionModeDECISION-API|BUCKETING|BUCKETING_EDGEDECISION-APIThe SDK running mode. see Decision Mode
fetchNowbooleantrueDetermines whether to automatically fetch flags data when creating a new Visitor.
timeoutnumber2The timeout in seconds for API requests.
Note: timeout can't be lower than 0 second.
reuseVisitorIdsbooleantrueclient-side only
If true, the SDK will save the visitor ID and/or anonymous ID and reuse it for the next session if visitorId is not set, to maintain cross-session visitor experience.
logLevelnumber9The maximum log level to display. seeLogLevel
logManagerobjectDefinedA custom implementation of the LogManager interface to receive logs from the SDK.
Note: The object must fill Interface IFlagshipLogManager
decisionApiUrlstringhttps://decision.flagship.io/v2This 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.
pollingIntervalnumber5Bucketing mode only
The delay in seconds between two bucketing polling requests.

Note:If 0 is given, it will only poll once at start time.
hitDeduplicationTimenumber2.5The delay in seconds for hit deduplication. After a hit is sent, any future attempts to send the same hit will be blocked until the specified delay has expired.

Note: If the value is 0, no deduplication process will be used.
initialBucketingobjectundefinedOptional
An object containing the data received when fetching the bucketing endpoint.
Providing this object will make bucketing ready to use and the first polling will immediately check for updates.
visitorCacheImplementationobjectDefined on client side and undefined on server sideOptional
An object that implements the visitorCacheImplementation interface to handle the visitor cache. see cache management
hitCacheImplementationobjectDefined on client side and undefined on server sideOptional
An object that implements the IHitCacheImplementation , interface to manage hits cache. see cache management
disableCachebooleanfalseIf set to true, hit cache and visitor cache will be disabled; otherwise, they will be enabled.. See cache management
onSdkStatusChangedfunction(number):voidundefinedOptional
A callback function to be called when the SDK status has changed. See arguments.
onBucketingSuccessfunction(object):voidundefinedOptional
A callback function to be called when the first bucketing polling succeeds. See arguments
onBucketingFailfunction(error):voidundefinedOptional
A callback function to be called when the first bucketing polling fails. See arguments
onBucketingUpdatedfunction(object):voidundefinedOptional
A callback function to be called each time bucketing data from Flagship has been updated. See arguments
onLogfunction(level: LogLevel, tag: string, message: string):voidundefinedOptional
A callback function to be called whenever the SDK needs to report a log.
see arguments
trackingManagerConfigobjectdefinedOptions to configure hit batching.
Tracking Manager Config
onVisitorExposedfunction(object):voidundefinedOptional
A callback function to be called each time a flag is exposed to a visitor (i.e., when an activation hit is sent by the SDK).

see arguments
fetchThirdPartyDatabooleanfalseOptional
Bucketing mode only
If true, the SDK will fetch the visitor's segment from the universal data connector each time fetchFlags is called and append those segments in the visitor context.
nextFetchConfigobject{ revalidate: 20 }Optional
In Next.js 13, you can define the time in seconds for storing SDK route cache before revalidation. learn more
fetchFlagsBufferingTimenumber2Optional

The delay in seconds for buffering fetch flags calls. After the SDK has fetched flags, they will be buffered for the specified delay. During this delay, any subsequent fetch flags calls will return the same flags.

Note:

- If a value of 0 is given, no buffering process will be used.

- If visitor data has changed, the buffering will be bypassed.
disableDeveloperUsageTrackingbooleanfalse Determines whether to disable the collection of analytics data.

Example:

import { Flagship, DecisionMode, CacheStrategy, LogLevel } from "@flagship.io/js-sdk";
//For Deno: import { Flagship, DecisionMode, CacheStrategy, LogLevel } from "https://deno.land/x/flagship_io_js_sdk/mod.ts";

Flagship.start("<ENV_ID>", "<API_KEY>", {
  decisionMode: DecisionMode.BUCKETING,
  timeout: 10,
  reuseVisitorIds: true,
  logLevel: LogLevel.CRITICAL,
  trackingManagerConfig: {
      cacheStrategy: CacheStrategy.PERIODIC_CACHING,
      poolMaxSize: 10,
      batchIntervals: 100
  },
});

Decision Mode

DECISION-API Mode (by default)

When the SDK is running in DecisionApi mode, the campaign assignments and targeting validation take place server-side in the flagship infrastructure. In this mode, each call to the fetchFlags method to refresh the flags will make an HTTP request.

Bucketing Mode

In Bucketing mode, the SDK downloads all campaign configurations in a single bucketing file. This allows the SDK to compute variation assignments on the client-side. The bucketing file is cached and only re-downloaded when campaign configurations are updated in the Flagship interface. Learn more

BUCKETING_EDGE Mode

This mode is recommended in Edge environnements, the SDK must be initialized with the bucketing file ,and the variation assignment is computed locally by the SDK.

There is no automatic batching process, so the Flagship.close() method must be called manually to batch and send all hits once collected. Learn more

DecisionMode is an enum defined decision type

KeyValueTypeDescription
DECISION_APIDECISION-APIstringFlagship SDK mode Decision API
BUCKETINGBUCKETINGstringFlagship SDK mode bucketing
BUCKETING_EDGEBUCKETING_EDGEstringFlagship SDK mode bucketing edge

LogLevel

LogLevel is an enum defined the level of log to receive

import { LogLevel } from "@flagship.io/js-sdk";

const level = LogLevel.ERROR;

Flagship.start("<ENV_ID>", "<API_KEY>", {
  logLevel: LogLevel.ERROR
});
KeyValueTypeDescription
NONE0intLogging will be disabled.
EMERGENCY1intOnly emergencies will be logged
ALERT2intOnly alerts and above will be logged.
CRITICAL3intOnly critical and above will be logged.
ERROR4intOnly errors and above will be logged.
WARNING5intOnly warnings and above will be logged.
NOTICE6intOnly notices and above will be logged.
INFO7intOnly info logs and above will be logged.
DEBUG8intOnly debug logs and above will be logged.
ALL9intEverything will be logged.

IFlagshipLogManager

The aims of this Interface is to define methods that an object must have in order to receive Flagship SDK logs

interface IFlagshipLogManager {
  emergency(message: string, tag: string): void;
  alert(message: string, tag: string): void;
  critical(message: string, tag: string): void;
  error(message: string, tag: string): void;
  warning(message: string, tag: string): void;
  notice(message: string, tag: string): void;
  info(message: string, tag: string): void;
  debug(message: string, tag: string): void;
  log(level: LogLevel, message: string, tag: string): void;
}
ArgumentTypeDescription
messagestringGet a description of the log
tagstringGet the function that triggered the log
levelnumberGet the log level.

Note: only for log method see LogLevel

Usage :

import { LogLevel, Flagship } from "@flagship.io/js-sdk";

const customLog = {
  emergency(message, tag) {
    this.log(LogLevel.EMERGENCY, message, tag);
  },

  alert(message, tag) {
    this.log(LogLevel.ALERT, message, tag);
  },

  critical(message, tag) {
    this.log(LogLevel.CRITICAL, message, tag);
  },

  error(message, tag) {
    this.log(LogLevel.ERROR, message, tag);
  },

  warning(message, tag) {
    this.log(LogLevel.WARNING, message, tag);
  },

  notice(message, tag) {
    this.log(LogLevel.NOTICE, message, tag);
  },

  info(message, tag) {
    this.log(LogLevel.INFO, message, tag);
  },

  debug(message, tag) {
    this.log(LogLevel.DEBUG, message, tag);
  },

  log(level, message, tag) {
    console.log(`[${LogLevel[level]}] [${tag}] : ${message}`);
  },
};

Flagship.start("<ENV_ID>", "<API_KEY>", {
  logManager: customLog,
  logLevel: LogLevel.ALL
});
import { LogLevel, Flagship } from "https://deno.land/x/flagship_io_js_sdk/mod.ts";

const customLog = {
  emergency(message, tag) {
    this.log(LogLevel.EMERGENCY, message, tag);
  },

  alert(message, tag) {
    this.log(LogLevel.ALERT, message, tag);
  },

  critical(message, tag) {
    this.log(LogLevel.CRITICAL, message, tag);
  },

  error(message, tag) {
    this.log(LogLevel.ERROR, message, tag);
  },

  warning(message, tag) {
    this.log(LogLevel.WARNING, message, tag);
  },

  notice(message, tag) {
    this.log(LogLevel.NOTICE, message, tag);
  },

  info(message, tag) {
    this.log(LogLevel.INFO, message, tag);
  },

  debug(message, tag) {
    this.log(LogLevel.DEBUG, message, tag);
  },

  log(level, message, tag) {
    console.log(`[${LogLevel[level]}] [${tag}] : ${message}`);
  },
};

Flagship.start("your_env_id", "your_api_key", {
  logManager: customLog,
  logLevel: LogLevel.ALL,
  fetchNow: false,
  timeout: 2,
});

FSSdkStatus

FSSdkStatus is an enum defining the different status of Flagship SDK

import { FSSdkStatus } from "@flagship.io/js-sdk";

const status = FSSdkStatus.SDK_INITIALIZED;
import { FSSdkStatus } from "https://deno.land/x/flagship_io_js_sdk/mod.ts";

const status = FSSdkStatus.SDK_INITIALIZED;
KeyValueTypeDescription
SDK_NOT_INITIALIZED0intIt is the default initial status. This status remains until the sdk has been initialized successfully.
SDK_INITIALIZING1intThe SDK is currently initializing.
SDK_PANIC2intFlagship SDK is ready but is running in Panic mode: All features are disabled except the one which refreshes this status.
SDK_INITIALIZED3intThe Initialization is done, and Flagship SDK is ready to use.

onSdkStatusChanged

The onSdkStatusChanged function has one argument

ArgumentTypeDescription
statusnumberStatus of the SDK. seeFSSdkStatus

onBucketingSuccess

The onBucketingSuccess function has one argument with the following shape:

Key/PropertyTypeDescription
statusnumberString. Returns either 200 (fresh update) or 304 (no change).
payloadobjectThe latest bucketing data received.

onBucketingFail

The onBucketingFail function has one argument

ArgumentTypeDescription
errorobjectReturns the error occurred

onBucketingUpdated

The onBucketingUpdated function has one argument

ArgumentTypeDescription
lastUpdateDateGet the date of the latest update

OnVisitorExposed

In some cases, you'll need to send information about the exposure (When a flag has been seen by your visitor), like sending visitor and flag data to third parties.

To centralize it, we provide a callback in the configuration option of the SDK.

The OnVisitorExposed function has one argument with the following shape:

ArgumentTypeDescription
paramOnVisitorExposedGet data from exposed flag

OnVisitorExposed shape

type OnVisitorExposed ={
    exposedVisitor: {
      id: string
      anonymousId?:string|null
      context: Record<string, string|number|boolean>
  },
    fromFlag: {
      key: string
      value: unknown
      defaultValue: unknown
      metadata: IFlagMetadata
  }
}
Key/PropertyTypeDescription
exposedVisitorobjectThis object represent the exposed visitor
fromFlagobjectThis object represent the exposed flag.
(The flag that has triggered the exposure)

exposedVisitor object shape

Key/PropertyTypeDescription
idstringvisitor id
anonomousIdstringanonymous id
contextRecord<string, string|number|boolean>visitor context

fromFlag object shape

Key/PropertyTypeDescription
keystringflag key
valueunknownflag value
defaultValueunknownflag default value
metadataIFlagMetadataCampaign information metadata see

Here is an example on how to use this callback:

Example with Mixpanel integration
Example with Segment integration

Learn more about getting flags

onLog

The onLog function has 3 arguments

ArgumentTypeDescription
levelnumberGet the log level. see LogLevel
tagstringGet the function that triggered the log
messagestringGet a description of the log
import { LogLevel, Flagship } from "@flagship.io/js-sdk";


Flagship.start("<ENV_ID>", "<API_KEY>", {
  logLevel: LogLevel.ALL,
  onLog: (level, tag, message) => {
    console.log(`[${LogLevel[level]}] [${tag}] : ${message}`);
  }
});

Tracking Manager Config

Represents the configuration for the tracking manager.

The Tracking Manager’s batch processing reduces network traffic, prevents hit loss through caching, and resends any failed hits.

options:

KeyTypeDefault valueDescription
cacheStrategyCacheStrategy | numberCONTINUOUS_CACHING: 0 for browser
PERIODIC_CACHING: 1 for nodeJs and Deno
Define the strategy that will be used for hit caching
see cacheStrategy
poolMaxSizenumber10 for browser
100 for nodeJs and Deno
Define the minimum number of hits the pool must reach to automatically batch all hits in the pool and send it

Note:

- Must be greater than 5 otherwise default value will be used
- Having a large poolMaxSize can lead to performance issues
batchIntervalsnumber5s for browser
10s for nodeJs and Deno
Define a regular interval in seconds to trigger batch processing

Note:

- The process will batch all hits from the pool whether poolMaxSize is reached or not
- Must be between 1sec and 10800s (3hours). Otherwise default value will be applied

CacheStrategy

cacheStrategy is an enum defining the different caching strategies

KeyTypevalueDescription
CONTINUOUS_CACHINGnumber0When a hit is emitted, it will first be cached in database using IHitCacheImplementation and added into the pool, then after batching and sending, it will also be flushed from database using IHitCacheImplementation.

Note:

- It is Recommended for client side applications and should be used when your application is running in an environment where the probability of data loss is high.
- The SDK has a default cache implementation for browser using localStorage
- Keep in mind that this strategy can do a lot of database I/O depending on how many hits your visitor can send.see example using localStorage
PERIODIC_CACHINGnumber1When a hit is emitted, it will be added into the pool, then after batching and sending, all database hits will be flushed, then the entire pool will be cached using IHitCacheImplementation for both actions.

Note:

- It is recommended for server-side applications and should be used when your application sends a lot of hits and the probability of data loss is low.
- The number of I/Os in the database is low.see example using redis

Example:

import { CacheStrategy, Flagship } from "@flagship.io/js-sdk";


Flagship.start(ENV_ID, API_KEY, {
    trackingManagerConfig: {
      cacheStrategy: CacheStrategy.PERIODIC_CACHING,
      poolMaxSize: 10,
      batchIntervals: 100
    }
 })

Visitor class

The Visitor class represents a unique user within your application. It aids in managing the visitor's data and fetching the corresponding flags for the visitor from the Flagship platform .

visitorId property

The unique visitor identifier.

  • visitorId: string

anonymousId property

The anonymous visitor identifier.

  • anonymousId: string | null

fetchStatus property

The fetch status of the flags. seeFetchFlagsStatus

  • fetchStatus: FetchFlagsStatus

hasConsented property

Return True if the visitor has consented for private data usage, otherwise, it returns False.

  • hasConsented: boolean

context property

This property returns all the visitor's current context as an object

  • get context () : Record<string, string | number | boolean>

setConsent method

Set if visitor has consented for protected data usage.

  • setConsent(hasConsented: boolean): void

Argument:

NameTypeDefaultDescription
hasConsentedbooleanrequiredSet visitor consent for private data usage. When false some features will be deactivated.

πŸ“˜

Information

When a visitor sets consent to false, the data collection features (visitorExposed and sendHit) will be deactivated for them and all hits related to the visitor will be flushed from the pool and the cache.

updateContext method

Update the visitor context values, matching the given keys, used for targeting.

A new context value associated with this key will be created if there is no previous matching value.

  • public updateContext(context: Record<string, string | number | boolean>): void

Argument:

NameTypeDescription
contextobjectA Set of keys, values.

clearContext method

Clear the actual visitor context

  • clearContext(): void

πŸ“˜

Information

  • Visitor context keys must have a type of string
  • Visitor context values must have a type of string, bool, numeric
  • Visitor context keys and values are case sensitive

Context with predefined keys of context

Here's an example of how to use these predefined keys to update the visitor context in both Node.js and Deno environments:

import { Flagship, DEVICE_LOCALE, OS_NAME } from "@flagship.io/js-sdk";

Flagship.start("your_env_id", "your_api_key");

const visitor = Flagship.newVisitor({
  visitorId: "your_visitor_id",
  context: { age: 31, isVip: true },
});

visitor.updateContext({
  [DEVICE_LOCALE]: "fr",
  [OS_NAME]: "Ubuntu",
});
import { Flagship, DEVICE_LOCALE, OS_NAME } from "https://deno.land/x/flagship_io_js_sdk/mod.ts";

Flagship.start("your_env_id", "your_api_key");

const visitor = Flagship.newVisitor({
  visitorId: "your_visitor_id",
  context: { age: 31, isVip: true },
});

visitor.updateContext({
  [DEVICE_LOCALE]: "fr",
  [OS_NAME]: "Ubuntu",
});

Here is the List of all predefined context keys.

fetchFlags method

Invokes the decision API or refers to the bucketing file to refresh all campaign flags based on the visitor's context.

  • fetchFlags(): Promise<void>

Example:

//... import code

Flagship.start("your_env_id", "your_api_key");

const visitor = Flagship.newVisitor({
  visitorId: "your_visitor_id",
  context: { key: "value" },
});

visitor.fetchFlags().then(() => {
  //ready to use all features from the SDK
});

Event listeners

The Visitor instance includes event listeners to help you handle the SDK.

Event listenerDescription
readyis triggered each time the fetchFlags method completes its execution.

getFlag method

Return a Flag object by its key. If no flag matches the given key, an empty flag will be returned. the exists() method of the Flag object can be called to check if the flag has been found.

  • getFlag(key:string):IFlag

Arguments:

NameTypeDescription
keyStringThe key associated to the flag.

authenticate method

Authenticate anonymous visitor.

  • authenticate(visitorId: string): void

Argument:

NameTypeDefaultDescription
visitorIdstringrequiredId of the new authenticated visitor.

πŸ“˜

Information

  • It is recommended calling the fetchFlags method just after authenticating a visitor as the visitor data has changed.
  • The visitor targeting / Flags could change based on this new data.

unauthenticate method

This method changes authenticated Visitor to anonymous visitor.

  • unauthenticate(): void

πŸ“˜

Information

  • It is recommended calling the fetchFlags method just after the visitor has become anonymous as the visitor data has changed.
  • The visitor targeting / Flags could change based on this new data.

getFlags method

Returns a collection of all flags fetched for the visitor.

  • getFlags(): IFSFlagCollection

sendHit method

This method sends a single Hit to the Flagship servers for reporting.

  • sendHit (hit: IHit): Promise<void>
ParameterTypeDefaultDescription
hitobjectrequiredHit to send. see Hit

sendHits method

This function sends multiple Hits to the Flagship servers for reporting.

  • sendHits (hits: IHit[]): Promise<void>
ParameterTypeDefaultDescription
hitArray<object>requiredA set of Hit to send. see Hit

IFSFlag interface

This interface represents a flag in the Flagship SDK. It helps you retrieve the flag value, access flag metadata, expose the flag, verify the flag's existence, and get the flag status with the following API:

metadata property

It returns an object that implements the IFSFlagMetadata interface, which contains the metadata of the campaign’s flag. If the flag doesn’t exist, it returns an empty object.

  • metadata:IFSFlagMetadata

status property

Return the flag status.

  • status: FSFlagStatus

FSFlagStatus is an enum representing the status of the flag

KeyTypeDescription
FETCHEDstringThe flags have been successfully fetched from the API or re-evaluated in bucketing mode.
FETCH_REQUIREDstringThe flags need to be re-fetched due to a change in context, or because the flags were loaded from cache or XPC.
NOT_FOUNDstringThe flag was not found or does not exist.
PANICstringThe SDK is in PANIC mode: All features are disabled except for the one to fetch flags.

getValue method

Returns the value of the flag if the flag exists and the type of the default value matches the flag type value, otherwise it returns the default value.

  • getValue<T>(defaultValue: T, visitorExposed : boolean) : T

Argument:

NameTypeDefault ValueDescription
defaultValueTRequiredRequiredThe default value of the flag.
visitorExposedBooleantrueIndicates to Flagship that the visitor have been exposed and have seen this flag. This will increment the visits for the current variation on your campaign reporting.
It is possible to set this param to false and call visitorExposed() afterward when the visitor sees it.

Example:

//other code

const flag = visitor.getFlag("displayVipFeature")

console.log("flag value:", flag.getValue(false))

πŸ“˜

Information

  • The default value must be one of the following type : string, number, boolean, object, array or null.
  • When the default value is null, no type checking will be performed

visitorExposed method

Notifies Flagship that the visitor has been exposed to and seen this flag.

  • visitorExposed(): Promise<void>

exists method

This method checks if the flag exists.

  • exists(): boolean

IFSFlagCollection interface

It represents a collection of flags.

size property

Gets the number of flags in the collection.

  • readonly size: number

get method

It returns the flag associated with the specified key, or an empty if the key is not found.

  • get(key: string): IFSFlag

Arguments:

NameTypeDescription
keyStringThe key associated to the flag.

has method

Checks if the collection contains a flag with the specified key.

  • has(key: string): boolean

Arguments:

NameTypeDescription
keyStringThe key associated to the flag.

keys method

Gets the keys of all flags in the collection.

  • keys(): Set<string>

filter method

It filters the collection based on a predicate function and returns A new IFSFlagCollection containing the flags that satisfy the predicate.

  • filter(predicate: (value: IFSFlag, key: string, collection: IFSFlagCollection) => boolean): IFSFlagCollection;

Arguments:

NameTypeDescription
predicatefunctionThe predicate function used to filter the collection.

exposeAll method

Exposes all flags in the collection.

  • exposeAll(): Promise<void>

getMetadata method

A map containing the metadata for all flags in the collection.

  • getMetadata(): Map<string, IFSFlagMetadata>;

toJSON method

Serializes the metadata for all flags in the collection.

  • toJSON(): SerializedFlagMetadata[]

forEach method

Iterates over each flag in the collection.

  • forEach (callbackfn: (value: IFSFlag, key: string, collection: IFSFlagCollection) => void): void

IFSFlagMetadata interface

interface IFSFlagMetadata{
    campaignId:string
  	campaignName:string
    variationGroupId:string
  	variationGroupName:string
    variationId: string
  	variationName:string
    isReference: boolean
    campaignType: string
    slug?:string|null
}
KeyTypeDescription
campaignIdstringCampaign ID
campaignNamestringCampaign name
variationGroupIdstringVariation group ID
variationGroupNamestringVariation group Name
variationIdstringThe variation ID assigned to the visitor
variationNamestringVariation name
isReferencebooleanSpecify if its the reference variation
campaignTypestringcampaign type
slugstringcampaign slug

SerializedFlagMetadata

KeyTypeDescription
keystringFlag name
campaignIdstringCampaign ID
campaignNamestringCampaign name
slugstringcampaign slug
campaignTypestringcampaign type
variationGroupIdstringVariation group ID
variationGroupNamestringVariation group name
variationIdstringThe variation ID assigned to the visitor
variationNamestringVariation name
isReferencebooleanSpecify if its the reference variation
hexstringReserved for Flagship

Hit Tracking

This section guides you on how to track visitors in your application and learn how to build hits to feed your reports. For more details about our measurement protocol, refer to our Universal Collect documentation.

There are five different types of Hits:

  • Page
  • Screen
  • Transaction
  • Item
  • Event

HitType

import { HitType } from "@flagship.io/js-sdk";

const page = HitType.PAGE;
import { HitType } from "https://deno.land/x/flagship_io_js_sdk/mod.ts";

const page = HitType.PAGE;
KeytypeValueDescription
PAGEstringPAGEVIEWIndicates a URL viewed by a visitor.
SCREENstringSCREENVIEWIndicates a screen viewed by a visitor.
TRANSACTIONstringTRANSACTIONIndicates a transaction made by a visitor.
ITEMstringITEMRepresents an item purchased in a transaction.
EVENTstringEVENTIndicates a specific action performed by a visitor.

Common Optional Parameters for Hits

import { HitType } from "@flagship.io/js-sdk";

visitor.sendHit({
  type: HitType.PAGE,
  documentLocation: "https://localhost",
  userIp: "127.0.0.1",
  screenResolution: "800X600",
  locale: "fr",
  sessionNumber: "1234",
});
import { HitType } from "https://deno.land/x/flagship_io_js_sdk/mod.ts";

visitor.sendHit({
  type: HitType.PAGE,
  documentLocation: "https://localhost",
  userIp: "127.0.0.1",
  screenResolution: "800X600",
  locale: "fr",
  sessionNumber: "1234",
});
ParameterTypeDescription
userIpString(Optional) Visitor's IP address
screenResolutionstring(Optional) Screen resolution.
localeString(Optional) Visitor's language
sessionNumberstring(Optional) Session number

Page hit

This hit should be sent each time a visitor navigates to a new page.

import { HitType } from "@flagship.io/js-sdk";

visitor.sendHit({
  type: HitType.PAGE, //or "PAGEVIEW"
  documentLocation: "https://www.my_domain_com/my_page",
});
import { HitType } from "https://deno.land/x/flagship_io_js_sdk/mod.ts";

visitor.sendHit({
  type: HitType.PAGE, //or "PAGEVIEW"
  documentLocation: "https://www.my_domain_com/my_page",
});

A Page type hit has the following structure:

Key/PropertyTypeDefaultDescription
typestring (PAGEVIEW)requiredtype of hit. see HitType
documentLocationStringrequiredValid url.

Screen hit

This hit should be sent each time a visitor navigates to a new interface on the client side.

import { HitType } from "@flagship.io/js-sdk";

visitor.sendHit({
  type: HitType.SCREEN, //or "SCREENVIEW"
  documentLocation: "home_screen",
});
import { HitType } from "https://deno.land/x/flagship_io_js_sdk/mod.ts";

visitor.sendHit({
  type: HitType.SCREEN, //or "SCREENVIEW"
  documentLocation: "home_screen",
});

A Screen type hit has the following structure:

Key/PropertyTypeDefaultDescription
typestring (SCREENVIEW)requiredType of hit. see HitType
documentLocationStringrequiredName of screen.

Transaction hit

This hit should be sent when a visitor completes a Transaction.

import { HitType } from "@flagship.io/js-sdk";

visitor.sendHit({
  type: HitType.TRANSACTION, //or "TRANSACTION"
  transactionId: "#12345",
  affiliation: "affiliation",
  taxes: 19.99,
  currency: "USD",
  couponCode: "code",
  itemCount: 1,
  shippingMethod: "road",
  shippingCosts: 5,
  paymentMethod: "credit_card",
  totalRevenue: "199.99",
});
import { HitType } from "https://deno.land/x/flagship_io_js_sdk/mod.ts";

visitor.sendHit({
  type: HitType.TRANSACTION, //or "TRANSACTION"
  transactionId: "#12345",
  affiliation: "affiliation",
  taxes: 19.99,
  currency: "USD",
  couponCode: "code",
  itemCount: 1,
  shippingMethod: "road",
  shippingCosts: 5,
  paymentMethod: "credit_card",
  totalRevenue: "199.99",
});

A hit of type TRANSACTION has this following structure:

Key/PropertyTypeDefaultDescription
typestring (TRANSACTION)requiredType of hit. see HitType
transactionIdStringrequiredUnique identifier for your transaction.
affiliationStringrequiredThe name of the KPI that you will have inside your reporting. Learn more
totalRevenuefloatoptionalThe total revenue associated with the transaction, including any shipping and/or tax amounts.
shippingCostsfloatoptionalThe total shipping cost of your transaction.
shippingMethodStringoptionalThe shipping method for your transaction.
taxesfloatoptionalSpecifies the total amount of taxes in your transaction.
currencyStringoptionalSpecifies the currency of your transaction. NOTE: This value should be a valid ISO 4217 currency code.
paymentMethodStringoptionalSpecifies the payment method used for your transaction.
itemCountintoptionalSpecifies the number of items in your transaction.
couponCodeStringoptionalSpecifies the coupon code used by the customer in your transaction.

Item hit

This hit is used to associate an item with a transaction. It should be sent following the corresponding transaction hit.

import { HitType } from "@flagship.io/js-sdk";

visitor.sendHit({
  type: HitType.ITEM, //or "ITEM"
  transactionId: "#12345",
  productName: "product",
  productSku: "sku123",
  itemPrice: 199.99,
  itemQuantity: 1,
  itemCategory: "test",
});
import { HitType } from "https://deno.land/x/flagship_io_js_sdk/mod.ts";

visitor.sendHit({
  type: HitType.ITEM, //or "ITEM"
  transactionId: "#12345",
  productName: "product",
  productSku: "sku123",
  itemPrice: 199.99,
  itemQuantity: 1,
  itemCategory: "test",
});

A hit of type ITEM has this following structure:

Key/PropertyTypeDefaultDescription
typestring (ITEM)requiredType of hit. see HitType
transactionIdStringrequiredUnique identifier for your transaction.
productNameStringrequiredName of your item.
productSkuStringrequiredSKU or item code.
itemCategoryStringoptionalCategory to which the item belongs.
itemPricefloatoptionalPrice for a single item/unit.
itemQuantityintoptionalSpecifies the number of items purchased.

πŸ“˜

Information

The Item hit is not currently available in the Flagship reporting view.

Event hit

This hit can be used to track any event, such as a click on 'Add To Cart' or a newsletter subscription.

import { HitType, EventCategory } from "@flagship.io/js-sdk";

visitor.sendHit({
  type: HitType.EVENT, //or "EVENT"
  category: EventCategory.USER_ENGAGEMENT, // or EventCategory.ACTION_TRACKING
  action: "click",
  label: "label",
  value: 100,
});
import { HitType, EventCategory } from "https://deno.land/x/flagship_io_js_sdk/mod.ts";

visitor.sendHit({
  type: HitType.EVENT, //or "EVENT"
  category: EventCategory.USER_ENGAGEMENT, // or EventCategory.ACTION_TRACKING
  label: "label",
  value: 100,
});

An EVENT type hit has the following structure:

Key/PropertyTypeDefaultDescription
typestring (EVENT)requiredType of hit. see HitType
categorystringrequiredCategory of your event.
NOTE: This value must be either User Engagement or Action Tracking.
actionstringrequiredEvent name, which will also serve as the KPI in your reporting. Learn more
labelstringoptionalAdditional description of your event.
valueintegeroptionalCan be used to evaluate visitor interactions with individual site objects or content items.
NOTE: this value must be non-negative and not a float

Cache management

The purpose of cache management is to address the following issues:

  • Re-allocation in bucketing mode :

In bucketing mode, the SDK ensures that a visitor remains in the variation where they were initially allocated, even if the customer or dynamic allocation changes the traffic allocation. This is because in bucketing mode, the assignment is made on the local device, so changing campaign allocation on the platform could cause visitors to see different campaigns.

  • Handle offline mode on client side :

When the cache is enabled, the SDK attempts to retrieve the latest visitor data (campaign assignments) from the cache. It also saves all failed hits and visitor exposures to resend them later.

By default, the Flagship JS SDK provides a default cache manager implementation on the client side. However, you can use your own cache manager by implementing the IVisitorCacheImplementation and IHitCacheImplementation interfaces through the visitorCacheImplementation and hitCacheImplementation properties of the configuration.

Visitor Cache

The visitor cache is used to store the visitor data in a database through the IVisitorCacheImplementation interface which defines the methods that an object must implement to manager it.

interface IVisitorCacheImplementation {
    cacheVisitor(visitorId: string, data: VisitorCacheDTO):Promise<void>
    lookupVisitor(visitorId: string): Promise<VisitorCacheDTO>
    flushVisitor(visitorId: string): Promise<void>
}

cacheVisitor method

This method is invoked when the SDK needs to store visitor information in your database.

  • public cacheVisitor(visitorId: string, data: object):Promise<void>

It accepts 2 arguments :

ArgumentTypeDescription
visitorIdstringThe ID of the visitor
DataobjectThe visitor data. The object adheres to the structure of the VisitorCacheDTO type.

lookupVisitor method

This method is invoked when the SDK needs to retrieve visitor information associated with a specific visitor ID from your database.

It should return an object of type VisitorCacheDTO that adheres to this structure see.

  • public lookupVisitor(visitorId: string): Promise<object>

It accepts one argument :

ArgumentTypeDescription
visitorIdstringvisitor ID

flushVisitor method

This method is invoked when the SDK needs to delete the visitor information associated with a specific visitor ID from your database.

It is invoked every time setConsent is set to false.

  • public flushVisitor(visitorId: string): Promise<void>

It accepts one argument :

ArgumentTypeDescription
visitorIdstringThe ID of the visitor

πŸ“˜

Information

  • flushVisitor method is called every time setConsent is set to false.

VisitorCacheDTO

type VisitorCacheDTO = {
  version: number;
  data: {
    visitorId: string;
    anonymousId: string | null;
    consent?: boolean;
    context?: Record<string, boolean|number|string>;
    assignmentsHistory?: Record<string, string>;
    campaigns?: Array<{
      campaignId: string;
      variationGroupId: string;
      variationId: string;
      isReference?: boolean;
      type: string;
      activated?: boolean;
      flags?: Record<string, unknown>;
    }>;
  };
};

Hit Cache

The hit cache is used to store hits in your database based on the strategy used through the IHitCacheImplementation interface which defines the methods that an object must implement to handle it.

interface IHitCacheImplementation {
    cacheHit(hits: Record<string, HitCacheDTO>):Promise<void>
    lookupHits():Promise<Record<string, HitCacheDTO>>
    flushHits(hitKeys: string[]): Promise<void>
    flushAllHits(): Promise<void>
}

cacheHit method

This method is invoked to store hits based on the strategy used.

  • public cacheHit(hits: Record<string, HitCacheDTO>):Promise<void>

It accepts 1 argument :

ArgumentTypeDescription
hitsobjectThis is a key/value object where:

- key is a unique ID for each hit
- value is an object that follows the shape of type HitCacheDTO.

lookupHits method

This method is invoked to load all hits from your database and attempt to send them in the background.

It should return an object where the key is a unique ID for each hit, and the value is an object of type HitCacheDTO that adheres to this structure see.

  • public lookupHits():Promise<Record<string, HitCacheDTO>>

flushHits method

This method is invoked to delete all hits that match the unique hit IDs from your database.

NOTE: It is called every time setConsent is set to false, erasing all of the visitor's hits from the database.

  • public flushHits(hitKeys: string[]): Promise<void>

It accepts one argument :

ArgumentTypeDescription
hitKeysArrayUnique ID of hits

flushAllHits function

This method is invoked to delete all hits from your database without exception.

  • public flushAllHits(): Promise<void>

HitCacheDTO

type HitCacheLookupDTO = {
  version: number;
  data: {
    visitorId: string;
    anonymousId: string | null;
    type: HitType | "ACTIVATE";
    time: number;
    content?: Record<string, unknown>;
  };
};

πŸ“˜

  • The flushHits method is called every time setConsent is set to false.
  • Hits older than 4H will be ignored during the resending process.

IHitCacheImplementation implementation

localStorage

This is an implementation of the IHitCacheImplementation interface using localStorage.

import { Flagship, CacheStrategy } from "@flagship.io/js-sdk";

const FS_HIT_PREFIX = 'FS_DEFAULT_HIT_CACHE'


const hitCacheImplementation = {
  cacheHit (hits) {
    const localDatabaseJson = localStorage.getItem(FS_HIT_PREFIX) || '{}'
    const localDatabase = JSON.parse(localDatabaseJson)

    const newLocalDatabase = {
      ...localDatabase,
      ...hits
    }

    localStorage.setItem(FS_HIT_PREFIX, JSON.stringify(newLocalDatabase))
    return Promise.resolve()
  },
  lookupHits () {
    const localDatabaseJson = localStorage.getItem(FS_HIT_PREFIX) || '{}'
    const localDatabase = JSON.parse(localDatabaseJson)
    return Promise.resolve(localDatabase)
  },
  flushHits (hitKeys) {
    const localDatabaseJson = localStorage.getItem(FS_HIT_PREFIX) || '{}'
    const localDatabase = JSON.parse(localDatabaseJson)

    hitKeys.forEach(key => {
      delete localDatabase[key]
    })

    localStorage.setItem(FS_HIT_PREFIX, JSON.stringify(localDatabase))
    return Promise.resolve()
  },
  flushAllHits () {
    localStorage.removeItem(FS_HIT_PREFIX)
    return Promise.resolve()
  }
}

Flagship.start(ENV_ID, API_KEY, {
  hitCacheImplementation: hitCacheImplementation,
  trackingManagerConfig: {
    batchIntervals: 5,
    poolMaxSize: 10,
    cacheStrategy: CacheStrategy.CONTINUOUS_CACHING
  }
})

Redis

This is an implementation of the IHitCacheImplementation interface using redis.

import { Flagship, CacheStrategy } from "@flagship.io/js-sdk";
import Redis from 'ioredis'

function hitCacheImplementation (host, port, dbIndex) {
  const redis = new Redis({
    host,
    port
  })

  redis.select(dbIndex)

  return {

    async cacheHit (hits) {
      const multi = redis.multi()
      Object.entries(hits).forEach(([key, value]) => {
        multi.set(key, JSON.stringify(value))
      })
      await multi.exec()
    },
    async lookupHits () {
      const hits:Record<string, HitCacheDTO> = {}
      const keys = await redis.keys('*')
      if (!keys.length) {
        return hits
      }
      const redisData = await redis.mget(keys)

      redisData.forEach((value, index) => {
        if (!value) {
          return
        }
        hits[keys[index]] = JSON.parse(value)
      })
      return hits
    },
    async flushHits (hitKeys) {
      await redis.del(hitKeys)
    },

    async flushAllHits () {
      const keys = await redis.keys('*')
      if (!keys.length) {
        return
      }
      await redis.del(keys)
    }
  }
}

Flagship.start(ENV_ID, API_KEY, {
  hitCacheImplementation:hitCacheImplementation('127.0.0.1', '6379', 2),
  trackingManagerConfig: {
    batchIntervals: 10,
    poolMaxSize: 100,
    cacheStrategy: CacheStrategy.PERIODIC_CACHING
  }
})

In the LocalStorage implementation, the localStorage web API is used to store, retrieve, and delete hits. In the Redis implementation, the ioredis library is used to interact with a Redis database for the same purposes. Both implementations are passed to the Flagship.start method as part of the configuration object.

Predefined visitor context keys

The Flagship SDK contains predefined visitor context keys.

The keys marked as Yes in the Auto-set by SDK column will be automatically set, while the ones marked as No need to be set by customer.

All possible predefined keys are listed below:

SDK constant NameDescriptionContext variable nameTypeAuto-set by SDKExample
DEVICE_LOCALELanguage of the devicesdk_deviceLanguageStringNofr
DEVICE_TYPEType of the devicesdk_deviceTypeDeviceTypeNoMobile
DEVICE_MODELModel of the devicesdk_deviceModelStringNosamsung E1200
LOCATION_CITYCity geolocationsdk_cityStringNotoulouse
LOCATION_REGIONRegion geolocationsdk_regionStringNooccitanie
LOCATION_COUNTRYCountry geolocationsdk_countryStringNoFrance
LOCATION_LATCurrent Latitudesdk_latDoubleNo43.623647
LOCATION_LONGCurrent Longitudesdk_longDoubleNo1.445397
OS_NAMEName of the OSsdk_osNameStringYESubuntu / centos
OS_VERSION_NAMEVersion name of the OSsdk_osVersionNameStringNo9.0.0
OS_VERSION_CODEVersion code of the OSsdk_osVersionCodeNumberNo24
CARRIER_NAMEName of the carrier or mobile virtual network operatorsdk_carrierNameStringNofree
INTERNET_CONNECTIONWhat is the internet connectionsdk_internetConnectionStringNo5g
APP_VERSION_NAMEVersion name of the appsdk_versionNameStringNo1.1.2-beta
APP_VERSION_CODEVersion code of the appsdk_versionCodeNumberNo40
INTERFACE_NAMEName of the interfacesdk_interfaceNameStringNoProductPage
FLAGSHIP_CLIENTFlagship SDK client (Reserved)fs_clientStringYesTS
FLAGSHIP_VERSIONVersion of the Flagship SDK (Reserved)fs_versionStringYes4.0.0
FLAGSHIP_VISITORCurrent visitor id (Reserved)fs_usersStringYesvisitor_id

πŸ“˜

Information

To overwrite the keys, use the updateContext method