The Optimization SDK Suite is pre-release (alpha). Breaking changes may be published at any time.
The Contentful Optimization API Client Library provides methods for interfacing with Contentful's Experience and Insights APIs, which serve its Personalization and Analytics products.
In the future, the Experience and Insights APIs may be combined behind an Optimization API
Install using an NPM-compatible package manager, pnpm for example:
pnpm install @contentful/optimization-api-client
Import the API client; both CJS and ESM module systems are supported, ESM preferred:
import { ApiClient } from '@contentful/optimization-api-client'
Configure and initialize the API Client:
const client = new ApiClient({ clientId: 'abc123' })
| Option | Required? | Default | Description |
|---|---|---|---|
analytics |
No | See "Analytics Options" | Configuration specific to the Analytics/Insights API |
clientId |
Yes | N/A | The Optimization API key |
environment |
No | 'main' |
The environment identifier |
fetchOptions |
No | See "Fetch Options" | Configuration for Fetch timeout and retry functionality |
personalization |
No | See "Personalization Options" | Configuration specific to the Personalization/Experience API |
Fetch options allow for configuration of both 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) => voidRetry behavior is intentionally fixed to HTTP 503 responses (Service Unavailable) for the
default SDK transport policy. This matches current Experience and Insights API expectations: 503
is treated as the transient availability signal, while other response classes are handled by
caller logic and are intentionally not retried by default. Treat this as deliberate contract
behavior, not a transport gap; broaden retry status handling only with an explicit API contract
change.
| Option | Required? | Default | Description |
|---|---|---|---|
baseUrl |
No | 'https://ingest.insights.ninetailed.co/' |
Base URL for the Insights API |
beaconHandler |
No | undefined |
Handler used to enqueue events via the Beacon API or a similar mechanism |
Configuration method signatures:
beaconHandler: (url: string | URL, data: BatchInsightsEventArray) => boolean| 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 |
All options except baseUrl may also be provided on a per-request basis.
Experience API methods are scoped to the client's experience member. All singular experience
methods return a Promise that resolves with the following data:
{
"profile": {
/* User profile data */
},
"personalizations": [
{
/* Personalization/experience configuration for the associated profile */
}
],
"changes": [
{
/* Similar to `personalizations` but currently used for Custom Flags */
}
]
}
const client = new ApiClient({ clientId: 'abc123' })
const { profile } = await client.experience.getProfile('profile-123', { locale: 'de-DE' })
const client = new ApiClient({ clientId: 'abc123' })
const { profile } = await client.experience.createProfile({ events: [...] }, { locale: 'de-DE' })
const client = new ApiClient({ clientId: 'abc123' })
const { profile } = await client.experience.updateProfile(
{
profileId: 'profile-123',
events: [...],
},
{ locale: 'de-DE' }
)
const client = new ApiClient({ clientId: 'abc123' })
const { profile } = await client.experience.upsertProfile(
{
profileId,
events: [...],
},
{ locale: 'de-DE' }
)
The upsertManyProfiles method returns a Promise that resolves with an array of user profiles.
The events array must contain at least one event. Each event should have an additional
anonymousId property set to the associated anonymous ID or profile ID.
const client = new ApiClient({ clientId: 'abc123' })
const profiles = await client.experience.upsertManyProfiles(
{
events: [
{
anonymousId: 'anon-123',
// valid Experience event payload fields
},
],
},
{ locale: 'de-DE' },
)
Insights API methods are scoped to the client's insights member. The batch send method returns a
Promise that resolves to boolean.
const client = new ApiClient({ clientId: 'abc123' })
await client.insights.sendBatchEvents([
{
profile: { id: 'abc-123', ... },
events: [
{
type: 'component',
componentId: 'hero-banner',
componentType: 'Entry',
variantIndex: 0,
...,
},
],
}
])
The Event Builder is a helper class that assists in constructing valid events for submission to the Experience and Insights APIs.
Event Builder configuration options assist in adding contextual data to each event created by a builder instance.
| Option | Required? | Default | Description |
|---|---|---|---|
app |
No | undefined |
The application definition used to attribute events to a specific consumer app |
channel |
Yes | N/A | The channel that identifies where events originate from (e.g. 'web', 'mobile') |
library |
Yes | N/A | The client library metadata that is attached to all events |
getLocale |
No | () => 'en-US' |
Function used to resolve the locale for outgoing events |
getPageProperties |
No | () => DEFAULT_PAGE_PROPERTIES |
Function that returns the current page properties |
getUserAgent |
No | () => undefined |
Function used to obtain the current user agent string when applicable |
The get* functions are most useful in stateful environments. Stateless environments should set the
related data directly via Event Builder method arguments.
The channel option may contain one of the following values:
webmobileserverConfiguration method signatures:
getLocale: () => string | undefined
getPageProperties:
() => {
path: string,
query: Record<string, string>,
referrer: string,
search: string,
title?: string,
url: string
}
getUserAgent: () => string | undefined
buildComponentClick: Builds a component click event payload for a Contentful entry-based
componentbuildComponentView: Builds a component view event payload for a Contentful entry-based componentbuildFlagView: Builds a component view payload event for a Custom Flag componentbuildIdentify: Builds an identify event payload to associate a user ID with traitsbuildPageView: Builds a page view event payloadbuildScreenView: Builds a screen view event payloadbuildTrack: Builds a track event payload for arbitrary user actionsSee the Event Builder documentation for more information regarding arguments and return values.
The Contentful Optimization API Client Library provides methods for interfacing with Contentful's Experience and Insights APIs, which serve its Personalization and Analytics products.