Contentful Personalization & Analytics
    Preparing search index...

    Module @contentful/optimization-node - v0.0.0

    Contentful Logo

    Contentful Personalization & Analytics

    Optimization Node SDK

    Readme · Reference · Contributing

    The Optimization Node SDK implements functionality specific to Node environments, based on the Optimization Core Library. This SDK is part of the Contentful Optimization SDK Suite.

    Table of Contents

    Install using an NPM-compatible package manager, pnpm for example:

    pnpm install @contentful/optimization-node
    

    Import the Optimization class; both CJS and ESM module systems are supported, ESM preferred:

    import Optimization from '@contentful/optimization-node'
    

    Configure and initialize the Optimization Node SDK:

    const optimization = new Optimization({ clientId: 'abc123' })
    

    Reference implementations illustrate how the SDK may be used under common scenarios, as well as select less-common scenarios, with the most basic example solution possible.

    • Node SSR: Example application that uses the Node SDK to render a personalized Web page
    • Node ESR: Example application demonstrating simple profile synchronization between the Node and Web SDKs via cookie
    Option Required? Default Description
    analytics No See "Analytics Options" Configuration specific to the Analytics/Insights API
    app No undefined The application definition used to attribute events to a specific consumer app
    clientId Yes N/A The Ninetailed API Key which can be found in the Ninetailed Admin app
    environment No 'main' The Ninetailed environment configured in the Ninetailed Admin app
    eventBuilder No See "Event Builder Options" Event builder configuration (channel/library metadata, etc.)
    fetchOptions No See "Fetch Options" Configuration for Fetch timeout and retry functionality
    logLevel No 'error' Minimum log level for the default console sin
    personalization No See "Personalization Options" Configuration specific to the Personalization/Experience API
    Option Required? Default Description
    baseUrl No 'https://ingest.insights.ninetailed.co/' Base URL for the Insights API

    Event builder options should only be supplied when building an SDK on top of the Optimization Node SDK or any of its descendent SDKs.

    Option Required? Default Description
    channel No 'server' The channel that identifies where events originate from (e.g. 'web', 'mobile')
    library No { name: 'Optimization Node API', version: '0.0.0' } The client library metadata that is attached to all events

    Fetch options allow for configuration of a Fetch API-compatible fetch method and the retry/timeout logic integrated into the Optimization API Client. Specify the fetchMethod when the host application environment does not offer a fetch method that is compatible with the standard Fetch API in its global scope.

    Option Required? Default Description
    fetchMethod No undefined Signature of a fetch method used by the API clients
    intervalTimeout No 0 Delay (in milliseconds) between retry attempts
    onFailedAttempt No undefined Callback invoked whenever a retry attempt fails
    onRequestTimeout No undefined Callback invoked when a request exceeds the configured timeout
    requestTimeout No 3000 Maximum time (in milliseconds) to wait for a response before aborting
    retries No 1 Maximum number of retry attempts

    Configuration method signatures:

    • fetchMethod: (url: string | URL, init: RequestInit) => Promise<Response>
    • onFailedAttempt and onRequestTimeout: (options: FetchMethodCallbackOptions) => void
    Option Required? Default Description
    baseUrl No 'https://experience.ninetailed.co/' Base URL for the Experience API
    enabledFeatures No ['ip-enrichment', 'location'] Enabled features which the API may use for each request
    ip No undefined IP address to override the API behavior for IP analysis
    locale No 'en-US' (in API) Locale used to translate location.city and location.country
    plainText No false Sends performance-critical endpoints in plain text
    preflight No false Instructs the API to aggregate a new profile state but not store it

    Arguments marked with an asterisk (*) are always required.

    Get the specified Custom Flag's value from the provided changes array.

    Arguments:

    • name*: The name/key of the Custom Flag
    • changes: Changes array

    Returns:

    • The resolved value for the specified Custom Flag, or undefined if it cannot be found.
    Note

    If the changes argument is omitted, the method will return undefined.

    Resolve a baseline Contentful entry to a personalized variant using the provided selected personalizations.

    Type arguments:

    • S: Entry skeleton type
    • M: Chain modifiers
    • L: Locale code

    Arguments:

    • entry*: The entry to personalize
    • personalizations: Selected personalizations

    Returns:

    • The resolved personalized entry variant, or the supplied baseline entry if baseline is the selected variant or a variant cannot be found.
    Note

    If the personalizations argument is omitted, the method will return the baseline entry.

    Resolve a "Merge Tag" to a value based on the provided profile. A "Merge Tag" is a special Rich Text fragment supported by Contentful that specifies a profile data member to be injected into the Rich Text when rendered.

    Arguments:

    • embeddedNodeEntryTarget*: The merge tag entry node to resolve
    • profile: The user profile
    Note

    If the profile argument is omitted, the method will return the merge tag's fallback value.

    Each method except trackFlagView may return an OptimizationData object containing:

    • changes: Currently used for Custom Flags
    • personalizations: Selected personalizations for the profile
    • profile: Profile associated with the evaluated events

    Identify the current profile/visitor to associate traits with a profile.

    Arguments:

    • payload*: Identify event builder arguments object, including an optional profile property with a PartialProfile value that requires only an id

    Record a personalization page view.

    Arguments:

    • payload*: Page view event builder arguments object, including an optional profile property with a PartialProfile value that requires only an id

    Record a personalization custom track event.

    Arguments:

    • payload*: Track event builder arguments object, including an optional profile property with a PartialProfile value that requires only an id

    Record an analytics component view event. When the payload marks the component as "sticky", an additional personalization component view is recorded. This method only returns OptimizationData when the component is marked as "sticky".

    Arguments:

    • payload*: Component view event builder arguments object, including an optional profile property with a PartialProfile value that requires only an id

    Track a feature flag view via analytics. This is functionally the same as a non-sticky component view event.

    Arguments:

    • payload*: Component view event builder arguments object, including an optional profile property with a PartialProfile value that requires only an id

    Interceptors may be used to read and/or modify data flowing through the Core SDK.

    • event: Intercepts an event's data before it is queued and/or emitted
    • state: Intercepts state data retrieved from an Experience API call before updating the SDK's internal state

    Example interceptor usage:

    optimization.interceptors.event((event) => {
    event.properties.timestamp = new Date().toISOString()
    })
    Warning

    Interceptors are intended to enable low-level interoperability; to simply read and react to Optimization SDK events, use the states observables.

    Classes

    AnalyticsStateful
    AnalyticsStateless
    ConsoleLogSink
    CoreStateful
    CoreStateless
    default
    EventBuilder
    InterceptorManager
    Logger
    LogSink
    PersonalizationStateful
    PersonalizationStateless
    ValuePresence

    Interfaces

    AnalyticsProductConfig
    AnalyticsProductConfigDefaults
    AnalyticsStates
    ApiClientConfig
    ApiConfig
    CoreConfig
    CoreConfigDefaults
    CoreStatefulConfig
    CoreStatelessConfig
    CoreStates
    EventBuilderConfig
    ExperienceApiClientConfig
    InsightsApiClientConfig
    LifecycleInterceptors
    LogEvent
    OptimizationNodeConfig
    PersonalizationProductConfig
    PersonalizationProductConfigDefaults
    PersonalizationStates
    PreviewPanelSignalObject
    ResolvedData
    Signal
    Signals

    Type Aliases

    AliasEvent
    AnalyticsStatefulOptions
    App
    AudienceEntry
    AudienceEntryFields
    BatchExperienceData
    BatchExperienceEvent
    BatchExperienceEventArray
    BatchExperienceResponse
    BatchInsightsEvent
    BatchInsightsEventArray
    Campaign
    Change
    ChangeArray
    Channel
    ComponentViewBuilderArgs
    ComponentViewEvent
    CtflEntry
    Dictionary
    EntryFields
    EntryReplacementComponent
    EntryReplacementVariant
    EntrySys
    ExperienceData
    ExperienceEvent
    ExperienceEventArray
    ExperienceEventType
    ExperienceRequestData
    ExperienceRequestOptions
    ExperienceResponse
    Flags
    GeoLocation
    GlobalApiConfigProperties
    GroupEvent
    IdentifyBuilderArgs
    IdentifyEvent
    InlineVariableComponent
    InsightsEvent
    InsightsEventArray
    InsightsEventType
    Interceptor
    Json
    Library
    LogLevels
    MergeTagEntry
    OptimizationData
    Page
    PageEventContext
    PageViewBuilderArgs
    PageViewEvent
    PartialProfile
    PersonalizationComponent
    PersonalizationComponentArray
    PersonalizationConfig
    PersonalizationEntry
    PersonalizationEntryArray
    PersonalizationFields
    PersonalizationStatefulOptions
    PersonalizationType
    PersonalizedEntry
    Profile
    Properties
    Screen
    ScreenEventContext
    ScreenViewBuilderArgs
    ScreenViewEvent
    SelectedPersonalization
    SelectedPersonalizationArray
    SessionStatistics
    TrackBuilderArgs
    TrackEvent
    TrackViewArgs
    Traits
    UniversalEventBuilderArgs
    UniversalEventContext
    UniversalEventProperties
    UnknownChange
    VariableChange

    Variables

    AliasEvent
    App
    AudienceEntry
    AudienceEntryFields
    BatchExperienceData
    BatchExperienceEvent
    BatchExperienceEventArray
    BatchExperienceResponse
    BatchInsightsEvent
    BatchInsightsEventArray
    Campaign
    Change
    ChangeArray
    ChangeType
    Channel
    ComponentViewEvent
    CtflEntry
    DEFAULT_PAGE_PROPERTIES
    Dictionary
    EntryFields
    EntryReplacementComponent
    EntryReplacementVariant
    EntrySys
    EXPERIENCE_BASE_URL
    ExperienceData
    ExperienceEvent
    ExperienceEventArray
    ExperienceRequestData
    ExperienceRequestOptions
    ExperienceResponse
    FlagsResolver
    GeoLocation
    GroupEvent
    IdentifyEvent
    InlineVariableComponent
    InlineVariableComponentValueType
    InlineVariableVariant
    INSIGHTS_BASE_URL
    InsightsEvent
    InsightsEventArray
    Library
    logger
    MergeTagEntry
    MergeTagValueResolver
    Page
    PageEventContext
    PageViewEvent
    PartialProfile
    PersonalizationComponent
    PersonalizationComponentArray
    PersonalizationConfig
    PersonalizationEntry
    PersonalizationEntryArray
    PersonalizationFields
    PersonalizationType
    PersonalizedEntry
    PersonalizedEntryResolver
    Profile
    Properties
    Screen
    ScreenEventContext
    ScreenViewEvent
    SelectedPersonalization
    SelectedPersonalizationArray
    SessionStatistics
    signals
    TrackEvent
    Traits
    UniversalEventContext
    UniversalEventProperties
    UnknownChange
    VariableChange
    VariableChangeValue

    Functions

    batch
    effect
    guardedBy
    isEntry
    isEntryReplacementComponent
    isEntryReplacementVariant
    isInlineVariableComponent
    isPersonalizationEntry
    isPersonalizedEntry