> For clean Markdown of any page, append .md to the page URL. > For a complete documentation index, see https://contentful.com/developers/docs/llms.txt. > For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://contentful.com/_mcp/server. # JavaScript SDK > Leverage custom instantiation options, methods, and properties for precise ontrol over accessing profile data, rendering experiences, and tracking functions. ## JavaScript SDK: The Ninetailed instance 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](/personalization/shared-sdk). A `Ninetailed` instance is created and provided when using the `` of React-based Ninetailed SDKs. For more information about the code, see the Ninetailed instance in our [open source SDK](https://github.com/ninetailed-inc/experience.js/blob/main/packages/sdks/javascript/src/lib/Ninetailed.ts). > **Info** > > Because a 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 underlying `NinetailedApiClient` in the [shared SDK](/personalization/shared-sdk). ## Dependencies and instantiation Ninetailed instances are created using a constructor from Ninetailed JavaScript SDK. ```TypeScript import { Ninetailed } from "@ninetailed/experience.js" // Instantiation const ninetailed = new Ninetailed( // Required ninetailedApiClientInstanceOrOptions, // Optional Options ) ``` ## Instantiation options ```TypeScript import type { NinetailedPlugin } from "@ninetailed/experience.js" import type { Ninetailed } from "@ninetailed/experience.js" import type { NinetailedAPIClient, NinetailedApiClientOptions, NinetailedRequestContext, OnErrorHandler, OnLogHandler } from "@ninetailed/experience.js-shared" type NinetailedApiClientInstanceOrOptions = NinetailedApiClient | NinetailedApiClientOptions; type Options = { buildClientContext?: () => NinetailedRequestContext; componentViewTrackingThreshold?: number; locale?: Locale; onError?: OnErrorHandler; onInitProfileId?: OnInitProfileId; onLog?: OnLogHandler; plugins?: (NinetailedPlugin | NinetailedPlugin[])[]; requestTimeout?: number; storageImpl?: Storage; url?: string; useSDKEvaluation?: boolean; } ``` ### `NinetailedApiClientInstanceOrOptions` Provide a created `NinetailedApiClient` instance (created using the Shared SDK [@ninetailed/experience.js-shared](/personalization/shared-sdk)), or supply parameters to create one. | Parameter | Type signature | Description | | :------------ | :---------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `clientId` | `clientId` | The organization ID/API key of a Ninetailed account. | | `environment` | `environment?: string` | The environment key of your account. Typically either `main` or `development`. Defaults to `main` if not specified. | | `fetchImpl` | `fetchImpl?: fetchImpl` | A `NinetailedApiClient` can be used in different JavaScript runtimes including the browser, Node.js, and edge workers. However, an implementation of the `fetch()` method available in the browser may not be available within all of those runtimes. This option allows you to provide a `fetch()` implementation of your own should the runtime not expose one automatically. | ### `Options` Specify optional configurations for the constructor. | Parameter | Type signature | Description | | :------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `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` | 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](/personalization/plugins). Plugins are used for a variety of purposes, including sending experience impression events, filtering events based on user consent, and previewing experiences. | | `plugins` | `plugins?: NinetailedPlugin[]` | Supply an array of [plugins](/personalization/plugins). Plugins are used for a variety of purposes, including sending experience impression events, filtering events based on user consent, and previewing experiences. | | `storageImpl` | `storageImpl?: { getItem: = (key: string) => T;` `setItem: = (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`. | ## Instance methods and properties | Property/Method | Type signature | Description | | :------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `page`, `track`, and `identify` | [See dedicated documentation](/personalization/experience-sdk#send-events). | Essential methods that submit events to the Experience API. See the [dedicated documentation](/personalization/experience-sdk#send-events/) 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 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` `type ElementSeenPayload = {
element: Element,
experience: {
id: string;
type: "nt_personalization" \| "nt_experience";
name?: string;
description?: string;
sticky?: boolean;
}
audience: {
id: string;
name?: string;
description: string;
}
variant: Record & { id: string};
variantIndex: number
}` | 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`\` \|Success \|` `Fail) => 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](/personalization/preview-plugin). 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` | `{
error: Error \| null,
from: "api" \| "hydrated"'
profile: Profile \| null,
status: "error" \| "loading" \| "success",
}` | 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` | 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`. | > Leverage custom instantiation options, methods, and properties for precise ontrol over accessing profile data, rendering experiences, and tracking functions.