Reference
Reference
Flagship class
Flagship classThe Flagship class represents the SDK. It facilitates the initialization process and creation of new visitors.
start method
start methodStarts the flagship SDK and returns the Flagship instance.
static start (envId: string, apiKey: string, config?: IFlagshipConfig): Flagship
Arguments:
envId
String
Required
Environment id provided by Flagship.
apiKey
String
Required
Api authentication key provided by Flagship.
config
Object
Optional
Custom 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>");
newVisitor method
newVisitor methodCreates and returns a new Visitor instance
This method should always be called after the Flagship SDK has started.
static newVisitor (params: INewVisitor): VisitornewVisitor (params: INewVisitor): Visitor
This method accepts only one argument with the following shape:
visitorId
string
undefined
Optional
Unique visitor identifier.
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).
hasConsented
boolean
false
Required 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.
isAuthenticated
boolean
false
Specify if the visitor is authenticated or anonymous for Experience continuity.
context
object { [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. Context keys must be strings, and the value types must be one of the following: number, boolean, or string.
shouldSaveInstance
boolean
false 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.
initialCampaigns
object
undefined
Optional 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.
initialFlagsData
array
undefined
Optional A set of flag data provided to avoid the SDK from having an empty cache during the first initialization.
onFetchFlagsStatusChanged
function(object):void
undefined
Optional Callback function that will be called when the fetch flags status changes. see arguments
📘 Information
When the property
fetchNowin the configuration is set totrue, the SDK will automatically fetch flag right after finishing creating the visitor.Visitor context keys must have a type of
stringVisitor context values must have a type of
string,boolean,numberVisitor context keys and values are case sensitive
When both
initialCampaignsandinitialFlagsare provided, the system will disregardinitialCampaignsand only useinitialFlags.
onFetchFlagsStatusChanged
The onFetchFlagsStatusChanged function has one argument
status
number
Status of the SDK. seeFetchFlagsStatus
FetchFlagsStatus object
FetchFlagsStatus is an object representing the status of visitor fetch for flag data.
status
object
Enum representing the status of the flags in the Flagship SDK.
reason
object
Enum representing the reasons for fetching Flags.
FSFetchStatus enum
FSFetchStatus is an enum representing the status of the flags in the visitor instance
FETCHED
string
The flags have been successfully fetched from the API or re-evaluated in bucketing mode.
FETCH_REQUIRED
string
The flags need to be re-fetched due to a change in context, or because the flags were loaded from cache or XPC.
NOT_FOUND
string
The flag was not found or does not exist.
PANIC
string
The 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.
AUTHENTICATE
string
Indicates that the XPC method 'authenticate' has been called.
FETCH_ERROR
string
Indicates that fetching flags has failed.
NONE
string
Indicates that there is no specific reason for fetching flags.
READ_FROM_CACHE
string
Indicates that flags have been fetched from the cache.
UPDATE_CONTEXT
string
Indicates that a context has been updated or changed.
UNAUTHENTICATE
string
Indicates that the XPC method 'unauthenticate' has been called.
VISITOR_CREATED
string
Indicates that the visitor has been created.
getStatus method
getStatus methodReturns current status of Flagship SDK. seeFSSdkStatus
getStatus (): FSSdkStatusstatic getStatus (): FSSdkStatus
getConfig method
getConfig methodReturns the current config used by the SDK. see configuration attribute
getConfig (): IFlagshipConfigstatic getConfig (): IFlagshipConfig
getVisitor method
getVisitor methodReturns the last visitor created and saved or return undefined if no visitor has been saved. see newVisitor.
getVisitor ():Visitor|undefinedstatic getVisitor ():Visitor|undefined
close method
close methodThis 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 :
decisionMode
DECISION-API|BUCKETING|BUCKETING_EDGE
DECISION-API
The SDK running mode. see Decision Mode
fetchNow
boolean
true
Determines whether to automatically fetch flags data when creating a new Visitor.
timeout
number
2
The timeout in seconds for API requests. Timeout can't be lower than 0 second.
reuseVisitorIds
boolean
true
client-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.
logLevel
number
9
The maximum log level to display. seeLogLevel
logManager
object
Defined
A custom implementation of the LogManager interface to receive logs from the SDK.
The object must fill Interface IFlagshipLogManager
decisionApiUrl
string
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.
pollingInterval
number
5
Bucketing mode only The delay in seconds between two bucketing polling requests. If 0 is given, it will only poll once at start time.
hitDeduplicationTime
number
2.5
The 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. If the value is 0, no deduplication process will be applied.
initialBucketing
object
undefined
Optional 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.
visitorCacheImplementation
object
Defined on client side and undefined on server side
Optional
An object that implements the visitorCacheImplementation interface to handle the visitor cache. see cache management
hitCacheImplementation
object
Defined on client side and undefined on server side
Optional
An object that implements the IHitCacheImplementation , interface to manage hits cache. see cache management
disableCache
boolean
false
If set to true, hit cache and visitor cache will be disabled; otherwise, they will be enabled.. See cache management
onSdkStatusChanged
function(number):void
undefined
Optional A callback function to be called when the SDK status has changed. See arguments.
onBucketingSuccess
function(object):void
undefined
Optional A callback function to be called when the first bucketing polling succeeds. See arguments
onBucketingFail
function(error):void
undefined
Optional A callback function to be called when the first bucketing polling fails. See arguments
onBucketingUpdated
function(object):void
undefined
Optional A callback function to be called each time bucketing data from Flagship has been updated. See arguments
onLog
function(level: LogLevel, tag: string, message: string):void
undefined
Optional A callback function to be called whenever the SDK needs to report a log. see arguments
trackingManagerConfig
object
defined
Options to configure hit batching. Tracking Manager Config
onVisitorExposed
function(object):void
undefined
Optional 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
fetchThirdPartyData
boolean
false
Optional
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.
nextFetchConfig
object
{ revalidate: 20 }
Optional In Next.js 13, you can define the time in seconds for storing SDK route cache before revalidation. learn more
fetchFlagsBufferingTime
number
2
Optional 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. If a value of 0 is given, no buffering process will be applied. If visitor data has changed, the buffering will be bypassed.
disableDeveloperUsageTracking
boolean
false
Determines whether to disable the collection of analytics data.
Example:
Decision Mode
DECISION-APIMode (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.
BucketingMode
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_EDGEMode
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.
DecisionMode is an enum defined decision type
DECISION_API
DECISION-API
string
Flagship SDK mode Decision API
BUCKETING
BUCKETING
string
Flagship SDK mode bucketing
BUCKETING_EDGE
BUCKETING_EDGE
string
Flagship SDK mode bucketing edge
LogLevel
LogLevel is an enum defined the level of log to receive
NONE
0
int
Logging will be disabled.
EMERGENCY
1
int
Only emergencies will be logged
ALERT
2
int
Only alerts and above will be logged.
CRITICAL
3
int
Only critical and above will be logged.
ERROR
4
int
Only errors and above will be logged.
WARNING
5
int
Only warnings and above will be logged.
NOTICE
6
int
Only notices and above will be logged.
INFO
7
int
Only info logs and above will be logged.
DEBUG
8
int
Only debug logs and above will be logged.
ALL
9
int
Everything 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
message
string
Get a description of the log
tag
string
Get the function that triggered the log
level
number
Get the log level.
only for log method see LogLevel
Usage :
FSSdkStatus
FSSdkStatus is an enum defining the different status of Flagship SDK
SDK_NOT_INITIALIZED
0
int
It is the default initial status. This status remains until the sdk has been initialized successfully.
SDK_INITIALIZING
1
int
The SDK is currently initializing.
SDK_PANIC
2
int
Flagship SDK is ready but is running in Panic mode: All features are disabled except the one which refreshes this status.
SDK_INITIALIZED
3
int
The Initialization is done, and Flagship SDK is ready to use.
onSdkStatusChanged
The onSdkStatusChanged function has one argument
status
number
Status of the SDK. seeFSSdkStatus
onBucketingSuccess
The onBucketingSuccess function has one argument with the following shape:
status
number
String. Returns either 200 (fresh update) or 304 (no change).
payload
object
The latest bucketing data received.
onBucketingFail
The onBucketingFail function has one argument
error
object
Returns the error occurred
onBucketingUpdated
The onBucketingUpdated function has one argument
lastUpdate
Date
Get 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:
param
OnVisitorExposed
Get data from exposed flag
OnVisitorExposed shape
exposedVisitor
object
This object represent the exposed visitor
fromFlag
object
This object represent the exposed flag. (The flag that has triggered the exposure)
exposedVisitor object shape
id
string
visitor id
anonomousId
string
anonymous id
context
Record<string, string
number
fromFlag object shape
key
string
flag key
value
unknown
flag value
defaultValue
unknown
flag default value
metadata
IFlagMetadata
Campaign information metadata see
Here is an example on how to use this callback:
Learn more about getting flags
onLog
The onLog function has 3 arguments
level
number
Get the log level. see LogLevel
tag
string
Get the function that triggered the log
message
string
Get a description of the log
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:
cacheStrategy
CacheStrategy | number
CONTINUOUS_CACHING: 0 for browser
PERIODIC_CACHING: 1 for nodeJs and Deno
Define the strategy that will be used for hit caching see cacheStrategy
poolMaxSize
number
10 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 them.
This value must be greater than 5; otherwise, the default value will be used.
Note: Having a large poolMaxSize can lead to performance issues.
batchIntervals
number
5s for browser
10s for nodeJs and Deno
Define a regular interval in seconds to trigger the batch process
The process will batch all hits from the pool whether the poolMaxSize is reached or not
The value must be between 1 second and 10800s (3 hours). Otherwise default value will be applied
CacheStrategy
cacheStrategy is an enum defining the different caching strategies
CONTINUOUS_CACHING
number
0
When a hit is emitted, it will first be cached in database using IHitCacheImplementation, added into the pool, then after batching and sending, it will be flushed from database using IHitCacheImplementation.
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_CACHING
number
1
When 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. 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:
Visitor class
Visitor classThe 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
visitorId propertyThe unique visitor identifier.
visitorId: string
anonymousId property
anonymousId propertyThe anonymous visitor identifier.
anonymousId: string | null
fetchStatus property
fetchStatus propertyThe fetch status of the flags. seeFetchFlagsStatus
fetchStatus: FetchFlagsStatus
hasConsented property
hasConsented propertyReturn True if the visitor has consented for private data usage, otherwise, it returns False.
hasConsented: boolean
context property
context propertyThis property returns all the visitor's current context as an object
get context () : Record<string, string | number | boolean>
setConsent method
setConsent methodSet if visitor has consented for protected data usage.
setConsent(hasConsented: boolean): void
Argument:
hasConsented
boolean
required
Set 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
updateContext methodUpdate 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:
context
object
A Set of keys, values.
clearContext method
clearContext methodClear the actual visitor context
clearContext(): void
📘 Information
Visitor context keys must have a type of
stringVisitor context values must have a type of
string,bool,numericVisitor 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:
Here is the List of all predefined context keys.
fetchFlags method
fetchFlags methodInvokes the decision API or refers to the bucketing file to refresh all campaign flags based on the visitor's context.
fetchFlags(): Promise<void>
Example:
Event listeners
The Visitor instance includes event listeners to help you handle the SDK.
ready
is triggered each time the fetchFlags method completes its execution.
getFlag method
getFlag methodReturn 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:
key
String
The key associated to the flag.
authenticate method
authenticate methodAuthenticate anonymous visitor.
authenticate(visitorId: string): void
Argument:
visitorId
string
required
Id 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
unauthenticate methodThis 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
getFlags methodReturns a collection of all flags fetched for the visitor.
getFlags(): IFSFlagCollection
sendHit method
sendHit methodThis method sends a single Hit to the Flagship servers for reporting.
sendHit (hit: IHit): Promise<void>
hit
object
required
Hit to send. see Hit
sendHits method
sendHits methodThis function sends multiple Hits to the Flagship servers for reporting.
sendHits (hits: IHit[]): Promise<void>
hit
Array<object>
required
A set of Hit to send. see Hit
IFSFlag interface
IFSFlag interfaceThis 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
metadata propertyIt 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
status propertyReturn the flag status.
status: FSFlagStatus
FSFlagStatus is an enum representing the status of the flag
FETCHED
string
The flags have been successfully fetched from the API or re-evaluated in bucketing mode.
FETCH_REQUIRED
string
The flags need to be re-fetched due to a change in context, or because the flags were loaded from cache or XPC.
NOT_FOUND
string
The flag was not found or does not exist.
PANIC
string
The SDK is in PANIC mode: All features are disabled except for the one to fetch flags.
getValue method
getValue methodReturns 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:
defaultValue
T
Required
Required The default value of the flag.
visitorExposed
Boolean
true
Indicates 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:
📘 Information
The default value must be one of the following type :
string,number,boolean,object,arrayornull.When the default value is
null, no type checking will be performed
visitorExposed method
visitorExposed methodNotifies Flagship that the visitor has been exposed to and seen this flag.
visitorExposed(): Promise<void>
exists method
exists methodThis method checks if the flag exists.
exists(): boolean
IFSFlagCollection interface
IFSFlagCollection interfaceIt represents a collection of flags.
size property
size propertyGets the number of flags in the collection.
readonly size: number
get method
get methodIt returns the flag associated with the specified key, or an empty if the key is not found.
get(key: string): IFSFlag
Arguments:
key
String
The key associated to the flag.
has method
has methodChecks if the collection contains a flag with the specified key.
has(key: string): boolean
Arguments:
key
String
The key associated to the flag.
keys method
keys methodGets the keys of all flags in the collection.
keys(): Set<string>
filter method
filter methodIt 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:
predicate
function
The predicate function used to filter the collection.
exposeAll method
exposeAll methodExposes all flags in the collection.
exposeAll(): Promise<void>
getMetadata method
getMetadata methodA map containing the metadata for all flags in the collection.
getMetadata(): Map<string, IFSFlagMetadata>;
toJSON method
toJSON methodSerializes the metadata for all flags in the collection.
toJSON(): SerializedFlagMetadata[]
forEach method
forEach methodIterates over each flag in the collection.
forEach (callbackfn: (value: IFSFlag, key: string, collection: IFSFlagCollection) => void): void
IFSFlagMetadata interface
IFSFlagMetadata interfacecampaignId
string
Campaign ID
campaignName
string
Campaign name
variationGroupId
string
Variation group ID
variationGroupName
string
Variation group Name
variationId
string
The variation ID assigned to the visitor
variationName
string
Variation name
isReference
boolean
Specify if its the reference variation
campaignType
string
campaign type
slug
string
campaign slug
SerializedFlagMetadata
key
string
Flag name
campaignId
string
Campaign ID
campaignName
string
Campaign name
slug
string
campaign slug
campaignType
string
campaign type
variationGroupId
string
Variation group ID
variationGroupName
string
Variation group name
variationId
string
The variation ID assigned to the visitor
variationName
string
Variation name
isReference
boolean
Specify if its the reference variation
hex
string
Reserved 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
PAGE
string
PAGEVIEW
Indicates a URL viewed by a visitor.
SCREEN
string
SCREENVIEW
Indicates a screen viewed by a visitor.
TRANSACTION
string
TRANSACTION
Indicates a transaction made by a visitor.
ITEM

