The Optimization SDK Suite is pre-release (alpha). Breaking changes may be published at any time.
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.
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 ContentfulOptimization from '@contentful/optimization-node'
Configure and initialize the Optimization Node SDK:
const optimization = new ContentfulOptimization({ clientId: 'abc123' })
const requestOptions = { locale: 'en-US' }
await optimization.page({}, requestOptions)
Create optimization once per module or process, then pass request-scoped Experience options as the
final argument to stateless event methods inside each incoming request.
The Node SDK is stateless, but that does not mean all request work is cacheable.
resolveOptimizedEntry() and getMergeTagValue() as request-local helpers when rendering.page(), identify(), screen(), track(), trackView(), trackClick(),
trackHover(), or trackFlagView(). Those methods emit outbound events and/or return profile
state for the current request.For a step-by-step Express-style walkthrough that covers request context, profile persistence, Contentful entry resolution, and hybrid Node + browser setups, see Integrating the Optimization Node SDK in a Node App.
The package-local dev harness runs from packages/node/node-sdk/dev/ and reads .env from this
package directory.
Start from .env.example and create or update packages/node/node-sdk/.env.
Prefer the repo-standard PUBLIC_... variable names shown in .env.example.
Start the harness from the repo root:
pnpm --filter @contentful/optimization-node dev
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.
| Option | Required? | Default | Description |
|---|---|---|---|
api |
No | See "API Options" | Unified configuration for the Experience API and Insights API endpoints |
app |
No | undefined |
The application definition used to attribute events to a specific consumer app |
clientId |
Yes | N/A | Shared API key for Experience API and Insights API requests |
environment |
No | 'main' |
The environment identifier |
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 sink |
| Option | Required? | Default | Description |
|---|---|---|---|
experienceBaseUrl |
No | 'https://experience.ninetailed.co/' |
Base URL for the Experience API |
insightsBaseUrl |
No | 'https://ingest.insights.ninetailed.co/' |
Base URL for the Insights API |
enabledFeatures |
No | ['ip-enrichment', 'location'] |
Enabled features the Experience API may use for each request |
Request-scoped Experience API options are passed to stateless event methods as their final argument instead of the SDK constructor:
| Option | Required? | Default | Description |
|---|---|---|---|
ip |
No | undefined |
IP address override used by the Experience API for location analysis |
locale |
No | undefined |
Locale used to translate location.city and location.country |
plainText |
No | undefined |
Sends performance-critical Experience API endpoints in plain text |
preflight |
No | undefined |
Instructs the Experience API to aggregate a new profile state but not store it |
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: '@contentful/optimization-node', 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 SDK's bundled API clients. 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) => voidArguments marked with an asterisk (*) are always required.
getFlagGet the specified Custom Flag's value from the provided changes array.
Arguments:
name*: The name/key of the Custom Flagchanges: Changes arrayReturns:
undefined if it cannot be found.Behavior notes:
getFlag(...) does not auto-emit trackFlagView.optimization.flagsResolver.resolve(changes).If the changes argument is omitted, the method will return undefined.
resolveOptimizedEntryResolve a baseline Contentful entry to an optimized variant using the provided selected optimizations.
Type arguments:
S: Entry skeleton typeM: Chain modifiersL: Locale codeArguments:
entry*: The baseline entry to resolveselectedOptimizations: Selected optimizationsReturns:
If the selectedOptimizations argument is omitted, the method will return the baseline entry.
getMergeTagValueResolve 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 resolveprofile: The user profileIf the profile argument is omitted, the method will return the merge tag's fallback value.
Pass request-scoped Experience options as the final argument to stateless event methods:
const requestOptions = {
locale: req.acceptsLanguages()[0] ?? 'en-US',
}
await optimization.page({ ...requestContext, profile }, requestOptions)
Request-scoped Experience options stay separate from the event payload. Event context such as page
data, locale metadata on the event, and user agent belong in payload, while ip, locale,
plainText, and preflight belong in requestOptions.
Only the following methods may return an OptimizationData object:
identifypagescreentracktrackView (when payload.sticky is true)trackClick, trackHover, and trackFlagView return no data. When returned, OptimizationData
contains:
changes: Currently used for Custom FlagsselectedOptimizations: Selected optimizations for the profileprofile: Profile associated with the evaluated eventsIn stateless runtimes, Insights-backed methods require a profile for delivery. Non-sticky
trackView, trackClick, trackHover, and trackFlagView require payload.profile.id. Sticky
trackView may omit profile, because the returned Experience profile is reused for the paired
Insights event.
identifyIdentify 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 idrequestOptions: Optional request-scoped Experience API options passed as the final argumentpageRecord an Experience API page view.
Arguments:
payload*: Page view event builder arguments object, including an optional profile property
with a PartialProfile value that requires only an idrequestOptions: Optional request-scoped Experience API options passed as the final argumentscreenRecord an Experience API screen view.
Arguments:
payload*: Screen view event builder arguments object, including an optional profile property
with a PartialProfile value that requires only an idrequestOptions: Optional request-scoped Experience API options passed as the final argumenttrackRecord an Experience API custom track event.
Arguments:
payload*: Track event builder arguments object, including an optional profile property with a
PartialProfile value that requires only an idrequestOptions: Optional request-scoped Experience API options passed as the final argumenttrackViewRecord an Insights API entry view event. When the payload marks the entry as "sticky", an additional
Experience API entry view is recorded. This method only returns OptimizationData when the entry is
marked as "sticky".
Arguments:
payload*: Entry view event builder arguments object. When payload.sticky is true, profile
is optional and the returned Experience profile is reused for Insights delivery. Otherwise,
profile is required and must contain at least an idrequestOptions: Optional request-scoped Experience API options passed as the final argument.
Only used when payload.sticky is truetrackClickRecord an Insights API entry click event.
Returns:
voidArguments:
payload*: Entry click event builder arguments object, including a required profile property
with a PartialProfile value that requires only an idrequestOptions: Optional request-scoped Experience API options accepted for signature
consistency; currently unusedtrackHoverRecord an Insights API entry hover event.
Returns:
voidArguments:
payload*: Entry hover event builder arguments object, including a required profile property
with a PartialProfile value that requires only an idrequestOptions: Optional request-scoped Experience API options accepted for signature
consistency; currently unusedtrackFlagViewTrack a feature flag view via the Insights API. This is functionally the same as a non-sticky flag view event.
Returns:
voidArguments:
payload*: Flag view event builder arguments object, including a required profile property
with a PartialProfile value that requires only an idrequestOptions: Optional request-scoped Experience API options accepted for signature
consistency; currently unusedInterceptors 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 emittedstate: Intercepts state data retrieved from an Experience API call before updating the SDK's
internal stateExample interceptor usage:
optimization.interceptors.event((event) => {
event.properties.timestamp = new Date().toISOString()
})
Interceptors are intended to enable low-level interoperability and should be used with care.
Contentful ContentfulOptimization Node SDK.
Remarks
Adds Node-specific defaults via the ContentfulOptimization class. Core and transitive API exports are available from dedicated entrypoints:
@contentful/optimization-node/core-sdk,@contentful/optimization-node/api-client, and@contentful/optimization-node/api-schemas.