JavaScript SDK: The Ninetailed Instance
Leverage custom instantiation options, methods, and properties for precise control over accessing profile data, rendering experiences, and tracking functions.
The Javascript SDK facilitates sending core Ninetailed events and tracking Ninetailed Experience views. These functions are managed by a created Ninetailed
class instance. Internally, the instance uses a NinetailedApiClient
instantiated by the Shared SDK.
A Ninetailed
instance is created and provided when using the <NinetailedProvider>
of React-based Ninetailed SDKs.
Because a Ninetailed class instance contains methods for tracking Experience views, it is mostly intended to be used client-side. For implementations where you want to render Experiences on the server, check out the Shared SDK's underlying NinetailedApiClient
.
Want to browse the code? Check out the Ninetailed instance in our open source SDK.
Dependencies and Instantiation
Ninetailed instances are created using a constructor from Ninetailed JavaScript SDK.
Instantiation Options
NinetailedApiClientInstanceOrOptions
NinetailedApiClientInstanceOrOptions
Provide a created NinetailedApiClient instance (created using the Shared SDK @ninetailed/experience.js-shared), or supply parameters to create one.
clientId
clientId
The organization ID/API key of a Ninetailed account.
environment
environment?: string
The environment key of a Ninetailed account. Typically either main
or development
, depending on the environment in which you have configured your content source connections. your you have configured Defaults to main
if unsupplied.
fetchImpl
fetchImpl?: fetchImpl
A NinetailedApiClient
can be used in different JavaScript runtimes including the browser, Node.js, and edge workers. However, a implementation of the fetch()
method available in the browser may not be available within all of those run times. This option allows you to provide a fetch()
implementation of your own should the runtime not expose one automatically.
Options
Options
Specify optional configurations for the constructor.
buildClientContext
buildClientContext?: () => {
url: string;
referrer: string;
locale: string;
userAgent: string;
document?: { title: string; } | undefined;
}
Supply a function to define a custom context object for events. Useful for working with React in non-web contexts.
componentViewTrackingThreshold
componentViewTrackingThreshold?: number
The amount of time in milliseconds an Experience must remain in the viewport to fire any connected plugin tracking calls. Defaults to 2000
.
locale
locale?: Locale;
Optionally specify a supported locale code.This will be used to localize location information.
onError
( message: string | Error, ...args: unknown[]) => void;
A logging function to be called on instance errors
onInitProfileId
(profileId?: string) => Promise<string | undefined> | string | undefined
Supply a callback function to assign the ID of a profile. This may be used to ensure that Ninetailed profiles use specific external IDs, e.g., those from a CDP, an ecommerce provider, or analytics instance.
onLog
(message: string | object, ...args: unknown[]) => void;
A logging function to be called on instance warn-level console messages
plugins
plugins?: NinetailedPlugin[]
Supply an array of Ninetailed plugins. Plugins are used for a variety of purposes, including sending experience impression events, filtering events based on user consent, and previewing experiences.
requestTimeout
requestTimeout?: number
The amount of time in milliseconds to wait for a response from the Experience API before falling back to baseline content. Defaults to 5000
.
storageImpl
storageImpl?: { getItem: <T = any> = (key: string) => T; setItem: <T = any> = (key: string, value: T) => void; removeItem: (key: string) => void; }
Specify a custom storage implementation. Ninetailed web SDKs default to using localStorage. Useful to store a Ninetailed profile anonymous ID client-side in non-web contexts.
url
url?: string
Specify the base URL of the Experience API to use when not supplying a NinetailedApiClient
as the NinetailedApiClientInstanceOrOptions
parameter. Defaults to "https://experience.ninetailed.co"
useSDKEvaluation
useSDKEvaluation?: boolean
Whether the Ninetailed instance should compute what experience and variants to assign for the current profile using the SDK (true
) or obtain these directly from the Experience API response (false
).
Use false
whenever possible. This option should be set to true
only when using a content source that does not index Ninetailed Experiences and Audiences on the Experience API. Defaults to false
.
Instance Methods and Properties
page
, track
, and identify
Essential methods of Ninetailed that submit events to the Experience API. See the dedicated documentation on these events.
batch
(events: Event[]) => Promise<{success: boolean}>
Guarantee multiple events are sent as single batch. Useful in conjunction with onRouteChange
to submit non-page events on initial route load.
debug
(enable: boolean) => void
Method to turn debug mode on or off. Debug mode logs information about profiles' assignment to experiences and its variants.
eventBuilder
EventBuilder
A class instance for building Ninetailed event method payloads based on the current context. The page
, track
, identify
, and component
methods use this internally.
Occasionally, you may need access to eventBuilder
directly when you need to build events without sending them right away, for example, if batching events together using the batch
method.
observeElement
(payload: ElementSeenPayload, options?: ObserveOptions) => void
Register a DOM element to be tracked by any plugins attached to the Ninetailed instance. Your plugin tracking events will fire when any part of the element has been visible within the user's viewport for at least the amount of time specified by the trackingComponentThreshold
configuration option on the Ninetailed instance. Internally calls trackComponentView
.
The return value of the instance method onSelectVariant
will provide much of the payload data of type ElementSeenPayload
(experience
, audience
, variant
, and variantIndex
).
onProfileChange
(profile: ProfileState) => void
Configure a callback function that is executed each time the profile changes. The callback function has access to the changed profile.
Additionally, the callback function you supply will be immediately invoked when first calling onProfileChange using the current profile state.
onRouteChange
({ isInitialRoute, url }: { isInitialRoute: boolean; url: string; }, ninetailed: NinetailedInstance) => void
[Exposed in Next.js and Gatsby SDKs only]
Supply a function to be called on each route change. When unspecified, the default is to call the page
method on each route change with no additional properties.
Most implementations should call the page
method on each route change even when other custom functionality is supplied, so ensure that your function does so.
onSelectVariant
({ baseline, experiences }: {baseline: Baseline, experiences: ExperienceConfiguration[]}, cb: (state: Loading<Baseline> | Success<Baseline, Variant> | Fail<Baseline>) => void) => void
Provide a baseline entry, its mapped experience entries, and a callback to execute. The callback has access to the currently selected variant for the supplied baseline/experience combination and will execute any time experience selections change. This method also responds to variants selected within a connected Preview widget. We suggest using this for the most declarative non-React implementations.
plugins
NinetailedPlugin[]
Read the plugins attached to the Ninetailed instance and/or invoke any methods attached to them.
profileState
Metadata about loading state of a profile and, once loaded, the current profile state.
reset
() => Promise
Discard the current profile state.
trackComponentView
(properties: ElementSeenPayload) => Promise<void>
Immediately send any connected plugin tracking calls for a supplied element. Called by observeElement
.
For custom implementations, we recommended using observeElement
over calling trackComponentView
directly.
unobserveElement
(element: Element) => void
Unregister an element for tracking. This is the clean up compliment to observeElement
.
Last updated