Forwarding Optimization SDK context to analytics and tag-management tools
Forwarding Optimization SDK context to analytics and tag-management tools
Overview
Use this guide when your application already sends events to an analytics, tag-management, customer-data, replay, or product-analytics destination and you want to attach approved Optimization SDK context to those events.
By the end, you can forward one approved SDK event or context signal to an app-owned destination without changing which events the SDK sends to Contentful.
This guide supplements the SDK integration guides. It does not install a vendor SDK, define a full tracking plan, or replace Contentful Analytics delivery. The Optimization SDK still sends its own events to Contentful. Your application decides which Contentful context, if any, can also reach a third-party destination.
Do you need this?
Use this guide when one of these statements is true:
- A report needs to break down existing events by Contentful experience, variant, entry, or Custom Flag value.
- A tag manager or CDP needs a small set of
contentful_*fields for routing or enrichment. - A server-rendered or native app already has an analytics event owner and needs request-local or runtime-local Optimization context.
Skip this guide when you only need Contentful Personalization and Analytics. The SDK already sends page, screen, entry interaction, Custom Flag, and profile-updating events to Contentful when your integration and consent policy allow them.
Quick start
Start with one app-level subscription in a stateful JavaScript runtime. Register it near SDK initialization, gate it with your destination consent policy, keep the message-ID cache outside the subscriber lifecycle, and forward only primitive fields.
Adapt this to your use case:
Keep the returned subscription for teardown in tests, hot reloads, or route-level provider
unmounts. The message-ID cache, not the subscription object, prevents re-forwarding across
subscriber or provider remounts. Remove the initial snapshot guard when forwarding the current
accepted SDK event at subscription time is intentional. Verify one SDK activity creates one intended
destination event before adding more vendors or fields. Use the helper in the default recipe when
the destination rejects undefined values or when exposure reports need view and hover
deduplication.
Default recipe
Use the same pattern for every destination:
- Pick the event owner. Use state streams for stateful clients, request-local event results for Node and server rendering, and existing business-event code for purchases, signups, leads, or other app-defined actions.
- Gate forwarding with the same application or CMP decision that controls the destination. SDK consent controls SDK event emission, not vendor consent modes.
- Deduplicate event-stream forwarding by
messageId. Keep the cache outside the subscriber or provider lifecycle so remounts can recognize the same current snapshot. When a subscriber must forward only events emitted after it registers, recordstates.eventStream.current?.messageIdbefore subscribing and skip that first message ID. - Collapse view and hover duration records before sending exposure or funnel events to a
third-party destination. SDK view and hover tracking can emit multiple records with the same
viewIdorhoverId. StickytrackView()also emits an Experience event and a paired Insights event for the same view. - Map only stable, primitive values. Prefer
contentful_*property names unless your tracking plan already defines destination-specific names. - Attach Contentful context to existing business events only when the report needs attribution by experience, variant, entry, or flag.
states.selectedOptimizations is useful for readiness checks and coarse segmentation, but it is not
an exposure event by itself. It tells you which experiences are active for the current profile, not
which entry rendered or which user interaction occurred.
The SDK event stream is a live handoff, not a durable third-party delivery queue. Stateful
JavaScript observables emit the current value when a subscriber registers, then later updates. They
do not replay the full history, and a new empty Set inside a new subscriber does not know which
current messageId an earlier subscriber already forwarded. Keep the message-ID cache in
longer-lived app state, or seed an initial message ID to skip when only later events belong in the
destination. iOS uses a Combine PassthroughSubject, and Android exposes a SharedFlow with a
finite recent-event replay buffer. Register native collectors before the page, screen, flag, or
entry interaction events that you need to own instead of treating either stream as a durable
analytics queue.
Optimized entry interaction events can include an optimization object on the event-stream payload.
That object is runtime-only enrichment for application subscribers; the SDK does not send it to the
Experience API or Insights API event payload. The enrichment can include the selected optimization,
the Optimization entry, the audience entry, the baseline entry, the resolved entry, and selected
variant metadata. Treat it as read-only and potentially large. Forward only approved primitive
fields, such as audience name or experience name, instead of forwarding the full object or complete
Contentful entries.
The optimization object is optional. It appears when the SDK can connect an interaction event to
an optimized entry resolution context. It is absent on events without that context, including
standalone Custom Flag view events.
Copy this:
If a destination can store engagement duration, aggregate by viewId or hoverId and send the
maximum or final duration value instead of dropping later duration records.
For Custom Flags, forward analytics from the same code path that reads or renders the flag. In
stateful SDKs, getFlag() and states.flag(name) or native flag observers can emit Contentful
flag-view tracking. Do not add an analytics-only flag subscription unless you intentionally want
that additional Contentful flag-view observation.
Runtime or vendor variants
Stateful JavaScript runtimes
Applies when you use the Web SDK, React Web SDK, React Native SDK, or app-local bound Next.js components and the SDK instance owns observable state.
For plain Web SDK integrations, subscribe directly on the SDK instance. For React Web and React
Native integrations, prefer onStatesReady on the provider root so the subscription exists before
child effects can emit SDK events.
For Next.js App Router integrations, configure onStatesReady once in
createNextjsAppRouterOptimization() from @contentful/optimization-nextjs/app-router. The bound
OptimizationRoot uses that factory config and renders without per-render clientId,
environment, or onStatesReady props. Use lower-level /client root props only for manual
server/client escape hatches.
For Pages Router integrations, configure onStatesReady once in
createNextjsPagesRouterOptimization() from @contentful/optimization-nextjs/pages-router, then
pass pageProps.contentfulOptimization.serverOptimizationState to the bound root in
pages/_app.tsx.
Adapt this to your use case:
Use states.blockedEventStream or onEventBlocked for diagnostics. Blocked events are dropped at
the SDK boundary and are not replayed when consent changes.
Node and Next.js server runtimes
Applies when a Node route, server action, middleware/proxy flow, or lower-level/manual Next.js server flow already called a request-bound SDK method and owns the analytics event for that request.
Use the data from the same accepted SDK call that rendered the response or handled the server
event. App Router Next.js integrations load request server data through the bound components created
by createNextjsAppRouterOptimization(). Use the config-bound getServerSideOptimizationProps()
helper for Pages Router getServerSideProps; it returns the same OptimizationData shape in its
data field and serializable props.contentfulOptimization. Use
getNextjsServerOptimizationData() only when you intentionally build a lower-level/manual /server
flow. When the SDK is configured with contentful: { client }, prefer the request-bound managed
entry helper so the entry decision and analytics context share the same request data. Browser state
streams cannot explain a server-rendered first paint unless you intentionally hydrate the browser
with the same Optimization data.
Adapt this to your use case:
For manual Contentful fetching, keep passing an app-fetched baselineEntry and
optimizationData?.selectedOptimizations to resolveOptimizedEntry(), then forward the same fields
from the returned result.
In stateless runtimes, Insights-only calls such as non-sticky trackView(), trackClick(),
trackHover(), and trackFlagView() need a request-bound profile. Sticky trackView() returns
Optimization data from the Experience path before sending the paired Insights event.
Native mobile runtimes
Applies when an iOS or Android app uses the native SDK and an app-owned analytics layer already collects events.
Subscribe from the screen or application owner that outlives the interactions you want to observe.
On iOS, eventStream is a Combine publisher backed by a PassthroughSubject, so subscribe before
calling page(), screen(), flagPublisher(...), or rendering tracked entries. On Android,
collect client.eventStream from a lifecycle-aware coroutine scope and cancel that scope with the
owning screen or activity.
iOS
Applies when a SwiftUI view model, UIKit controller, scene delegate, or app-level analytics owner
holds the AnyCancellable. Shape the dictionary before calling the vendor SDK because native events
can include fields that your destination has not approved.
Follow this pattern:
Android
Applies when a Compose screen, XML activity, or app-level analytics owner can collect from a
lifecycle-aware coroutine scope. Android keeps a finite recent-event replay buffer, so apply
messageId or semantic deduplication before forwarding if the collector can restart.
Follow this pattern:
Native events arrive as dictionary or map payloads with fields such as type, messageId,
componentId, experienceId, variantIndex, viewId, and viewDurationMs. Native mobile SDKs
expose view and tap tracking, not hover tracking; hoverId and hoverDurationMs apply to Web and
Node runtimes that emit hover events. Optimized entry interaction events can also include the same
optional optimization enrichment object. Keep the same mapping and consent rules that you use for
JavaScript destinations, and prefer approved display strings, such as audience name, over full
nested objects.
Destination variants
Use the destination shape that matches your analytics architecture:
GTM and dataLayer
Applies when Google Tag Manager owns routing to one or multiple vendor tags. Push one normalized object and register the corresponding data-layer variables inside the tag manager.
Follow this pattern:
Adobe Web SDK
Applies when Adobe Web SDK forwards event data to Adobe Experience Platform or downstream Adobe reporting. Keep the Contentful fields namespaced unless your approved tracking plan maps them to specific XDM fields.
Follow this pattern:
Register destination-specific custom dimensions, event properties, XDM fields, or data-layer variables before relying on reports. Keep vendor autocapture from duplicating SDK page, screen, click, tap, hover, or exposure events unless your tracking plan intentionally counts both.
Validate the integration
Verify the recipe before release:
- The SDK integration still sends expected events to Contentful when consent allows it.
- The third-party destination receives only the intended
contentful_*fields. - Denied or withdrawn consent blocks both SDK-gated events and third-party forwarding according to your application policy.
states.blockedEventStream, nativeblockedEventStream, oronEventBlockedshows expected blocked methods during consent tests.- Subscriber or provider remounts do not resend the same current
messageId; either the cache outlives the subscriber or the initial snapshot is intentionally skipped. - View and hover records are collapsed, summarized, or intentionally mirrored before reaching third-party exposure and funnel reports.
- Sticky view tracking produces one intended downstream exposure, not one Experience exposure plus one Insights exposure.
- Server-rendered first paint and browser follow-up tracking have one owner for each event in the tracking plan.
- Known-user identity uses your application user ID. The Optimization profile ID is metadata only when your policy allows forwarding it.
- Event-stream
optimizationenrichment is reduced to approved primitive fields, such as audience name or experience name, before it leaves the application boundary. - Full profile objects, audience membership lists, raw
changes, complete Contentful entries, and rich text bodies are absent from destination payloads unless the destination is explicitly approved for that data.
Governance notes
Treat this recipe as a data-routing decision, not as an SDK requirement.
The application owns the tracking plan, consent record, destination consent modes, retention rules, and deletion or suppression flows. SDK consent is a runtime gate for SDK events. It does not configure Google Consent Mode, tag-manager consent, warehouse routing, replay masking, ad-platform sharing, or product-analytics opt-out behavior.
Use the Optimization profile ID carefully. It is a profile-continuity identifier, not your known
user ID. Use your application user ID for vendor identify() calls, and forward the Optimization
profile ID only as approved event metadata.
Keep server, browser, and native event names aligned when they describe the same business behavior. When the same user action can happen in more than one runtime, document which runtime owns the third-party event and which runtime only sends Contentful SDK events.
Related guides and concepts
Use these guides when you need the SDK setup that this recipe assumes:
- Choose the right SDK
- Integrate the Optimization Node SDK in a Node app
- Integrate the Optimization Web SDK in a web app
- Integrate the Optimization React Web SDK in a React app
- Integrate the Optimization Next.js SDK in a Next.js App Router app
- Integrate the Optimization Next.js SDK in a Next.js Pages Router app
- Integrate the Optimization React Native SDK in a React Native app
- Integrate the Optimization iOS SDK in a SwiftUI app
- Integrate the Optimization iOS SDK in a UIKit app
- Integrate the Optimization Android SDK in a Compose app
- Integrate the Optimization Android SDK in a Views app
Use these concepts for mechanics behind the recipe:
- Consent management in the Optimization SDK Suite
- Interaction tracking in Web SDKs
- Interaction tracking in Node and stateless environments
- React Native SDK interaction tracking mechanics
- iOS SDK runtime and interaction mechanics
- Android SDK runtime and interaction mechanics
- Profile synchronization between client and server