Integrate the Optimization React Web SDK in a React app
Overview
Use this guide to add Contentful personalization to a client-side React app you already have — a single-page app built with Vite, Create React App, React Router, or a similar setup. By the end of the quick start, one piece of content will render its personalized variant in the browser once the SDK resolves it, without changing how your app fetches or renders content.
New to personalization? Here is the whole idea in four points:
- In Contentful you author variants of an entry and attach them to an experience — a rule that decides which visitors see which variant.
- As the visitor uses your app, Contentful’s Experience API looks at who they are and picks the variant for each experience. Swapping a fetched entry for its picked variant is called resolving the entry.
- Your app hands a Contentful entry to the SDK at the point where that entry becomes output. The SDK gives back the selected variant, or the original entry when no variant applies—the baseline fallback. You can fetch the entry yourself or give the SDK your Contentful client and an entry ID; either way, the client stays yours.
- You render the returned entry with the same application components you already use.
That is enough to start. The guide introduces policy and optional capabilities at the point you need them.
You will get there in two milestones:
- Milestone 1 — a personalized entry in the client render (the quick start below). After the SDK resolves, a visitor sees their variant on screen. This is complete and shippable on its own.
- Milestone 2 — live re-personalization (opt-in, later). Content re-resolves when consent, identity, or profile changes, without a full reload. See Live updates.
This guide uses @contentful/optimization-react-web, which wraps the lower-level
@contentful/optimization-web browser SDK in React providers, hooks, and an entry-rendering
component. You configure it by passing props to one OptimizationRoot component you mount once —
there is no separate factory call. Your app keeps ownership of the Contentful client, consent
policy, identity, routing, and rendering.
Because this SDK runs entirely in the browser, there is no server-rendered first paint: the SDK becomes ready after React mounts, so loading and error states are a first-class part of the integration, not an afterthought. If your app renders on the server (Next.js), use the Next.js App Router guide or the Next.js Pages Router guide instead; if your app is not React-based, or you want to own the browser SDK lifecycle without React abstractions, use the Web SDK guide.
Quick start
Most React + Contentful apps share one shape: you fetch an entry (a page, a hero, a section) and
render its fields through your own components. This quick start assumes that shape and personalizes
a single entry. In the snippets that change an existing file, lines prefixed with + are what you
add and the rest is a typical app for context — match the additions to your own file rather than
pasting the whole block. If your app is shaped differently, the change is the same wherever an entry
becomes a component; see
Resolving entries and rendering the result.
It proves one result: one entry renders its personalized variant in the browser once the SDK resolves it. Because the SDK is not ready synchronously, the entry shows a brief loading state first, then reveals the resolved content — that is expected, not a bug. This quick start assumes your app may personalize on startup; if personalization must wait for consent, keep this structure and add the Consent and privacy handoff step before you ship.
-
Install the package. Add
contentfultoo — a companion dependency you install alongside the SDK — if your app does not already have a Contentful Delivery API client.Copy this:
-
Mount
OptimizationRootonce, around every component that will use the SDK. Pass your Optimization project config as props. Use the same environment-variable convention your app already uses for browser-visible values (this example uses Vite’simport.meta.envwith aPUBLIC_prefix; adjust to your bundler).defaultsis the SDK’s starting browser state (consent, persistence, and similar). Inside it,consent: truetells the SDK it may personalize and send events for this visitor; the quick start uses always-on consent to keep the path simple — production gates this on the visitor’s choice (see Consent and privacy handoff).Adapt this to your use case: wrap your existing app tree; replace the placeholder env-var names with yours. The config keys are explained in How the SDK fits your app.
-
Fetch one Contentful entry and render it through
OptimizedEntry.OptimizedEntrytakes the entry you fetched asbaselineEntryand calls your render prop with the resolved entry — the variant when one applies, or the baseline entry otherwise. While the SDK is still resolving,OptimizedEntryshows the baseline as a hidden loading target and reveals the result once resolution settles.Adapt this to your use case: this is your page component. Your fetch, your Contentful client, and your markup stay yours; the pattern to copy is the fetch-in-effect and the
OptimizedEntrywrap. -
Check that it works. In Contentful, author a variant on the entry you fetch above and attach it to an experience — for a first test, target all visitors so you match it automatically. Load the app: you should see a brief loading state, then the variant’s text render in place of the baseline. If the baseline text stays on screen, work through Troubleshooting.
You now have personalization working. The rest of this guide is not a re-run of the quick start — it explains what each step did and covers what the quick start deliberately skipped: real, consent-gated startup; the SDK readiness and loading model; your Contentful fetch requirements and the baseline-fallback contract; page events and route tracking; interaction tracking; identity; live updates; and production hardening. Read straight through, or jump to the section you need.
Before you start
The sections below walk the integration in order. First, gather the few things you can only get from outside this guide:
- A React app (18.3 or newer) with React and React DOM installed, and its own Contentful
fetching already working.
contentfulis a companion dependency you install alongside the SDK if you do not already have a Delivery API client. - Contentful delivery credentials — space ID, delivery token, and environment.
- At least one entry with a variant attached to an experience, authored in Contentful. Without an authored variant, the integration can still run correctly while returning the baseline, so you cannot yet distinguish working personalization from a content-authoring gap. For the first personalized-content test, target all visitors so the test request or visitor matches automatically.
- Your Optimization project values — client ID and environment, from your Optimization project settings. The Experience and Insights API base URLs default correctly; you only set them for mocks or non-default hosts (see How the SDK fits your app).
You do not need a setup inventory up front. Everything else — consent, page events, tracking, identity, live updates — is introduced by the section that needs it.
The snippets use a PUBLIC_-prefixed import.meta.env convention (Vite). Use whatever mechanism your bundler uses to expose variables to browser code — process.env.REACT_APP_* for Create React App, import.meta.env.VITE_*, and so on — and keep it consistent with your other browser-visible Contentful variables.
Core integration
How the SDK fits your app
Integration category: Required for first integration
This section explains the OptimizationRoot you mounted in the quick start — what each prop does
and how to make startup depend on real consent.
OptimizationRoot is the single React entry point. It composes the OptimizationProvider and
LiveUpdatesProvider for you, creates the underlying Web SDK instance after React commits, and
destroys that instance on unmount. You configure the SDK by passing props directly to this
component, and you mount it exactly once around the subtree that uses the SDK.
The props you pass break down like this:
clientIdandenvironmentidentify your Optimization project. Read them from browser-safe env variables.localeis the one locale the SDK uses for Experience and event context. Use the same locale you pass to Contentful.defaultsis the browser SDK’s starting state:consent(may personalize and send events) andpersistenceConsent(may store the profile-id cookie — the anonymous identifier the SDK assigns each visitor to keep their variant assignments consistent across visits).apioverrides the Experience and Insights endpoints (experienceBaseUrl,insightsBaseUrl). Set these only for a mock, a proxy, or non-default hosts; omit them otherwise.appis your app’s name and version, sent as metadata.contentfulopts into managed entry fetching by handing the SDK your Contentful client (contentful: { client, defaultQuery?, cache? }); leave it unset to fetch entries yourself. See Fetching Contentful entries.liveUpdates,trackEntryInteraction, andonStatesReadyare optional and covered in their own sections below.
The quick start used always-on defaults to get you a result. For production, make startup depend
on real consent: leave consent unset (or seed it off) and call setConsent(true) from the UI that
owns the visitor’s decision, as shown in
Consent and privacy handoff.
The only import path you need to start is the package root, @contentful/optimization-react-web.
Other subpaths cover specific needs you reach for later:
Adapt this to your use case: the root with app metadata and API overrides, the way a real app configures it.
Mount OptimizationRoot exactly once. Mounting a second owned instance in the same browser runtime
throws ContentfulOptimization is already initialized. Do not nest OptimizationProvider inside
OptimizationRoot: the root already composes the provider and live-updates provider. If you need
direct provider control, use OptimizationProvider instead of OptimizationRoot; nesting an
injected provider shadows the root context, including prefetched managed entries.
SDK readiness, loading, and error states
Integration category: Required for first integration
This is the concept that has no equivalent in the server-rendered guides, so it is worth stating plainly. Because the SDK runs only in the browser, it is not ready on the first render. It is created after React commits, then it asks the Experience API who the visitor is. Two consequences follow, and both surface through hooks you already saw in the quick start:
- Reading the SDK instance.
useOptimizationContext()returns{ sdk, error }.sdkis defined from the first render (the provider seeds a read-only snapshot so hooks never crash), anderroris set only if initialization fails. Guard onerrorto render a fallback, as the quick start does. UseuseOptimization()instead when a component needs the SDK instance directly and can assume it is present — it throws if the SDK is unavailable, so it belongs belowOptimizationRootin code that runs after mount (event handlers, effects). - Reading an entry’s resolution state.
OptimizedEntryhandles its own loading: while it waits for the Experience API outcome, it renders the baseline entry as a hidden layout target so the page does not jump, then reveals the resolved content when resolution settles. If resolution never settles, it reveals the baseline after a 5-second timeout so the UI never hangs. PassloadingFallbackto show custom loading UI during that window instead.
Your own Contentful fetch is a separate concern from SDK readiness — you can start it in an effect on mount. The important rule is only about entry resolution: an entry with optimization references stays in its loading state until the Experience request settles, which is why you see a brief loading state before the variant appears.
- Render an app-level fallback when
useOptimizationContext().erroris set — personalization is unavailable, but decide whether the rest of your app should still render. - Let
OptimizedEntryown per-entry loading; addloadingFallbackonly where you want custom UI. - Do not block your whole app waiting for optimization state. Entries without optimization references render immediately after SDK initialization.
Follow this pattern: an app-level error fallback plus per-entry loading UI.
For components that need loading and readiness metadata directly — for example to disable a control
until optimizations are available — use useOptimizedEntry(), which returns
{ entry, isLoading, canOptimize, selectedOptimization, … } for one baseline entry.
Fetching Contentful entries
Integration category: Required for first integration
Your app always owns the Contentful client. There are two supported ways to get a fetched entry to the point where the SDK resolves it, and you can mix them per entry:
- Manual (the quick start’s path). Your code calls the Contentful client itself and passes the
result to
OptimizedEntryasbaselineEntry. Your fetching, caching, and response shaping stay entirely yours; the SDK only needs the entry to arrive in a shape it can resolve. - Managed (opt-in). You hand the SDK your Contentful client once via
contentful: { client }onOptimizationRoot, and then reference entries by id —<OptimizedEntry entryId="…">. The SDK fetches through your client’sgetEntry()andgetEntries()methods and resolves the result. This trades a little control for less wiring per entry; see Resolving entries and rendering the result for the managed component variant.
If you are just starting or want full control over fetching, stay on the manual path; switch to
managed when you would rather the SDK make the getEntry() call than write per-component fetch
code.
Both paths obey the same fetch rules, because the SDK resolves the same single-locale entry shape either way:
- Fetch with one concrete Contentful locale. Do not use
withAllLocalesor raw Contentful Delivery API (CDA)locale=*— all-locale payloads use locale-keyed field maps the resolver cannot read, so entries fall back to baseline. - Use an
includedepth deep enough to resolve the whole tree — the entry, its sections, and the linked variant entries.include: 10is the common setting. In the managed path the SDK appliesinclude: 10for you, and you can still override per call withentryQuery. - Pass the same locale to Contentful and to
OptimizationRootso localized Experience responses and rendered content line up. In the managed path the SDK falls back to theOptimizationRootlocalewhen your query does not set one.
A single-locale entry exposes its optimization fields directly, such as fields.nt_experiences and
fields.nt_variants (the nt_ prefix is how personalization links appear on an entry).
Copy this: the manual fetcher from the quick start. fetchPageEntry is your own helper — name
it whatever fits your app.
To use the managed path instead, pass that same client to OptimizationRoot and let the SDK fetch.
The contentful prop is SDK-owned; client is your app-owned Contentful client.
Adapt this to your use case: enable managed fetching on the root you already mount. The + line
is the only addition; the rest is the root from the quick start.
If your app changes locale at runtime, OptimizationRoot updates the SDK’s Experience and event
locale when its locale prop changes. On the manual path you still refetch Contentful entries and
re-emit page events yourself; on the managed path a changed entryId/entryQuery refetches, but
you still re-emit page events yourself. For the full model, see
Locale handling in the Optimization SDK Suite.
Resolving entries and rendering the result
Integration category: Required for first integration
Step 3 showed the wrap. This explains the two things about it that matter everywhere. The rule never
changes: wherever a Contentful entry becomes a component, wrap it in OptimizedEntry and render
whatever the render prop hands back.
- Type of the resolved entry. The render prop’s first argument is typed as a base
contentfulEntry. If your component expects a narrower type, cast it —resolved as YourEntryType— which mirrors the reference implementation. This direct cast works for the common cases, including.withoutUnresolvableLinks-narrowed types. Only if TypeScript rejects a cast for a genuinely disjoint type do you needresolved as unknown as YourEntryType. - Fallback contract. When consent is denied, no variant applies, links are unresolved, or the payload was all-locale, the render prop simply receives the baseline entry. Your UI never breaks; it falls back to default content — this is why the quick start renders correctly even before you author a variant.
The quick start wrapped an entry directly in a page. The other common shape is a renderer or registry that maps a content type to a component; wrapping it there personalizes every entry it renders. The wrap and the cast are identical.
Adapt this to your use case: a content-type-to-component renderer (yours may be named
differently). The + lines are the additions; keep your existing guards.
OptimizedEntry must render under an ancestor that handles useOptimizationContext().error (as the
readiness section shows). On an SDK initialization
failure it throws rather than rendering baseline, so an unguarded subtree crashes.
The managed alternative to baselineEntry. If you enabled managed fetching with
contentful: { client } (see Fetching Contentful entries), you can
pass entryId instead of fetching yourself. The two entry sources are mutually exclusive: an
OptimizedEntry takes either baselineEntry (manual — you fetched it) or entryId
(managed — the SDK fetches it), never both. With entryId, the SDK fetches through your client
while the component shows its loading state, then resolves and reveals exactly as the manual path
does. Two props exist only for the managed path, since only it can fail while fetching:
errorFallback— what to render if the managed fetch fails. It is a node or(error: Error) => ReactNode; returnundefinedto render nothing.onEntryError— a(error: Error) => voidcallback for logging or reporting the fetch failure.
Adapt this to your use case: the managed variant of the same wrap. entryQuery is optional and
overrides the merged managed query per call.
The render prop, the cast, and the baseline-fallback contract are identical to the manual path; only the entry source and the two managed-failure props differ.
Two more facts hold everywhere:
- Do not double-wrap the same entry. A nested
OptimizedEntrythat shares a baseline entry id with anOptimizedEntryabove it renders nothing (it returnsnull, with a dev-only warning). Wrap at one level — the renderer hand-off, or the individual cards, not both. Nested wrappers with different baseline ids are fine. OptimizedEntrywraps content in a layout-neutral element withdisplay: contentsby default, so it does not affect layout. Use theasprop when the wrapper must be a specific element; it accepts only'div'or'span'(default'div'), so it cannot be an arbitrary element such as'section'. It also accepts plain node children when the markup does not need the resolved entry; the wrapper still resolves metadata and emits tracking attributes.
For the resolver contract, see Entry personalization and variant resolution.
Page events and route tracking
Integration category: Required for first integration
A page event signals that a page or route was viewed. The Experience API uses page events to evaluate route-based experiences, so most integrations emit one on first load and on every route change. React Web ships auto page trackers for common routers; each dedupes consecutive route keys, including React Strict Mode’s double effects.
- Mount one tracker inside
OptimizationRootand inside the router context it reads. Use the tracker that matches your router. - Use
pagePayloadfor static fields andgetPagePayloadfor fields derived from the route context. Router-derived payload, staticpagePayload, and dynamicgetPagePayloadare deep-merged in that order; later values win on key conflicts. - For an app with no supported router, call
trackPageView()fromuseOptimizationActions()in your own route-change effect.
Most React SPAs use React Router, so this guide uses ReactRouterAutoPageTracker. (The next-pages
and next-app trackers exist for React-Web-only Next.js setups; a full Next.js integration should
use the dedicated Next.js SDK guides instead.)
Adapt this to your use case: the tracker mounted once in your router root.
To attach route-aware properties, pass getPagePayload:
Follow this pattern:
The next-pages and next-app trackers also accept initialPageEvent="skip" for setups where a
server path already emitted the first page event. In a browser-only React SPA you emit the first
page event yourself, so leave it at the default ("emit").
Consent and privacy handoff
Integration category: Common but policy-dependent
Consent policy belongs to your application. The SDK tracks two independent axes: consent (may
personalize and send events) and persistenceConsent (may store the profile-id cookie). Until
consent is set, the SDK permits only identify and page events; other events stay blocked.
- If policy permits personalization by default, seed accepted consent in
defaultsduring setup (as the quick start does). - If policy depends on user choice, leave
consentunset and callsetConsent(true | false)from the banner, Consent Management Platform (CMP) callback, or settings screen that owns the decision. - Use object-form consent —
setConsent({ events: true, persistence: false })— only when events and durable profile continuity have different policy decisions. A boolean sets both together. - Persist the visitor’s choice in your own store (a cookie,
localStorage, or account preference) so your UI can restore it on the next visit. That consent record is yours — you name, write, and read it. The SDK does not manage it; it only reflects what you pass tosetConsent().
Adapt this to your use case: a consent control wired to the SDK actions and to your own consent record.
The SDK stores its own consent, persistence-consent, and profile-continuity state in browser
storage; the browser-readable profile-id cookie is named ctfl-opt-aid and is the one persistence
value the SDK owns and manages. If storage writes fail, the SDK continues with in-memory state. For
the cross-SDK policy model, see
Consent management in the Optimization SDK Suite.
Entry interaction tracking
Integration category: Common but policy-dependent
Interaction tracking — views, clicks, and hovers on entries — is a browser behavior.
OptimizedEntry renders the tracking metadata the SDK needs, and the SDK observes interactions once
consent permits. It is on by default when you use OptimizedEntry, so you rarely configure anything
to get started.
- Leave the defaults on when your consent policy allows them. Use the
trackEntryInteractionprop onOptimizationRootonly to opt out of an interaction type you must not observe. - Use
OptimizedEntryprops —clickable,trackViews,trackClicks,trackHovers, and the duration-interval props — for per-entry control. - Page and identify events can be sent before full consent, but entry views, clicks, and hovers
stay blocked until consent (or
allowedEventTypes) permits them.
Tracking uses the resolved entry id, not the baseline id.
Follow this pattern: opting one detector out globally, plus a per-entry override.
For DOM that automatic observation cannot reach, resolve metadata with useOptimizedEntry() and
call sdk.tracking.enableElement('views', element, { data: … }) from an effect, clearing it with
sdk.tracking.clearElement(...) on unmount so recycled nodes do not keep stale entry data. For
detector behavior and data attributes, see
Interaction tracking in Web SDKs.
Identity, profile, and reset
Integration category: Common but policy-dependent
Identify a visitor only when your app knows who they are or has policy-approved traits to send. Reset profile state when the active visitor changes or logs out.
- Call
identifyUser()from the account, session, or profile event that owns the identity decision. - Render SDK state with dedicated hooks such as
useProfileState()anduseSelectedOptimizationsState(). - Call
resetUser()when identity changes must clear profile, selected optimizations, and route dedupe state. Consent state is preserved; clear your own consent record separately if withdrawal also ends consent. - Re-emit
trackPageView()oridentifyUser()after a reset when the app needs fresh optimization state.
Adapt this to your use case: an account panel wired to the SDK actions.
With live updates enabled, identifyUser(), setConsent(), and resetUser() can
change selected variants and re-render affected entries without a reload. For cross-runtime identity
behavior, see
Profile synchronization between client and server.
Optional integrations
Live updates
Integration category: Optional
This is Milestone 2. First render is already complete and shippable; add live updates only when some content must re-personalize after it first resolves — for example when a visitor accepts consent, signs in, or is identified, and entries should update without a reload.
Live updates are opt-in because most content is fixed once resolved. You do not add a provider — the
bound OptimizationRoot already includes the live-updates provider internally. You only choose the
scope:
- App-wide default: set
liveUpdatesonOptimizationRoot. Every entry without its own override re-resolves on state changes. - Per-entry: pass
liveUpdateson a specificOptimizedEntryto opt one entry in (liveUpdates) or out (liveUpdates={false}), independent of the app-wide default. - The preview panel forces live updates while it is open, regardless of these settings.
The effective precedence is: preview panel open, then the per-entry liveUpdates prop, then the
root liveUpdates prop, then the default (locked to the first resolved state).
Follow this pattern: the app-wide switch plus per-entry overrides.
To verify, enable live updates, then trigger identifyUser(), setConsent(), or resetUser().
Live entries re-resolve without a full reload; entries with liveUpdates={false} stay put until the
next render.
Merge tags and Custom Flags
Integration category: Optional
Use merge tags when Contentful Rich Text contains embedded profile-backed values (a personalized greeting, a location). Use Custom Flags when app UI branches on a named flag rather than an optimized entry.
- Inside an
OptimizedEntry, readgetMergeTagValuefrom the render prop’s second argument and pass it into your Rich Text renderer. - Use
useMergeTagResolver()only when you resolve merge tags outside anOptimizedEntryrender prop. - Merge tags live inside Rich Text as embedded entry nodes, so
getMergeTagValuetakes a merge-tag entry node. Guard each embedded entry withisMergeTagEntry(from/api-schemas) before resolving it. - For flags, read
optimization.getFlag(name)for a nonreactive read, or subscribe tooptimization.states.flag(name)when UI must re-render as the flag changes. Reading a flag can emit flag-view tracking when consent allows it.
Follow this pattern: resolving merge tags while rendering Rich Text.
Merge tags and entry replacement use different mechanics: entry replacement swaps the whole entry for its variant; merge tags read profile-backed values from current SDK state. Keep the SDK locale aligned with the rendered Contentful locale when merge tags reference localized profile fields.
Analytics forwarding
Integration category: Optional
Use analytics forwarding when your app needs to send approved Optimization context to a tag manager, customer-data platform, or analytics destination. The SDK still sends its own events to Contentful; forwarding is application-owned.
- Register the subscription with the
onStatesReadyprop so it attaches before child effects (such as route trackers) emit events. - Dedupe forwarded events by
messageId. To receive only future events, read the currentmessageIdbefore subscribing and skip it. - Store forwarded message ids in module or app state so remounts do not forward the same event again.
- Gate forwarding with the same consent and destination policy that governs the rest of your analytics stack.
Follow this pattern:
For diagnostics on events the SDK blocks by consent or allowedEventTypes, also subscribe to
states.blockedEventStream. For vendor mappings, consent boundaries, and dedupe guidance, see
Forwarding Optimization SDK context to analytics and tag-management tools.
Preview panel
Integration category: Optional
The preview panel is a separate browser package for authoring and staging workflows — including
forcing a specific variant to verify a targeted experience. It appends a panel to document.body
and talks to the Web SDK through the browser preview bridge.
- Install
@contentful/optimization-web-preview-panel. - Gate the dynamic import behind an environment variable so production bundles can drop it.
- Attach it after the SDK exists. The
onStatesReadyprop is a good attach point. - Pass an app-owned Contentful client, or pre-fetched preview entries, to the attach function.
Adapt this to your use case:
By default the attach function uses window.contentfulOptimization, which the provider creates in
the browser. If your app injects its own SDK instance, pass optimization to the attach function.
If you already load preview definitions (through GraphQL, a loader, or a proxy), pass
entries: { audiences, experiences } instead of contentful. Verify with live updates enabled,
because the panel forces optimized entries to react to preview state.
Advanced integrations
Owning the Web SDK instance
Integration category: Advanced or production-only
Use OptimizationProvider directly when an application or framework adapter must create and own the
Web SDK instance outside React.
- Create the Web SDK instance yourself with
@contentful/optimization-web. - Pass it through
OptimizationProvider sdk={optimization}. - Wrap children in
LiveUpdatesProviderif any component usesOptimizedEntry,useOptimizedEntry, oruseLiveUpdates.OptimizationRootdoes this for you; when you compose the providers yourself, you add it explicitly. - Destroy the injected instance in the owner that created it — the provider does not call
destroy()on instances it did not create.
Use this as an alternative to OptimizationRoot, not as a child of it. OptimizationRoot already
includes OptimizationProvider, and a nested provider creates a separate context for its subtree.
Adapt this to your use case:
The provider always renders its children — they are never withheld or unmounted. When you pass
serverOptimizationState, children render against a read-only snapshot until the live SDK state is
applied in a layout effect. With an injected sdk and no serverOptimizationState, children render
against the live injected SDK from the first render; onStatesReady alone does not add a snapshot
phase.
Prefetching managed entries for a server handoff. When a managed (entryId) OptimizedEntry
renders on a server before the browser SDK is live, you can hand it its baseline entry so it renders
resolved content immediately instead of a loading state. The package root exports the symbols for
this: prefetchManagedEntries(runtime, descriptors) returns a ManagedEntryHandoff[] you pass to
the prefetchedManagedEntries prop on OptimizationRoot (or OptimizationProvider), keyed by
entryId + entryQuery. descriptors are ManagedEntryDescriptor values ('entry-id' or
{ entryId, entryQuery? }); runtime is any ManagedEntryPrefetchRuntime — an object exposing
prefetchManagedEntries(descriptors). Core uses getEntries() for multiple uncached descriptors
with the same normalized query, split into 100-ID chunks for large fetches. This SDK ships no server
runtime of its own, so you supply that runtime yourself. For a full server-rendered integration with
request-scoped state and page-event handoff, use the
Next.js App Router guide or
Next.js Pages Router guide,
which own that path end to end.
Strict consent, storage, and delivery controls
Integration category: Advanced or production-only
Configure these only after your privacy, analytics, and platform owners agree on the event posture.
- Set
allowedEventTypes={[]}onOptimizationRootwhen no Optimization event may emit before explicit consent. (The default allowsidentifyandpage.) - Use
cookiewhen the profile-id cookie needs a specific domain or expiration. - Use
queuePolicywhen the default retry and offline-queue behavior does not match your limits. - Use
onEventBlocked(andstates.blockedEventStream) for diagnostics when consent orallowedEventTypesblock events.
Follow this pattern:
Blocked events are not replayed when consent later changes. If the current route, flag, or entry state still qualifies after consent, the SDK can emit a fresh current-state event.
Production checks
Run these checks before release:
- Confirm
clientId, environment,locale,apiendpoints, app metadata, and log level point to the intended environment, and that browser-exposed env variables contain only values safe to ship. - Confirm Contentful fetches use one concrete locale with a deep enough
include, and never passwithAllLocales/locale=*payloads toOptimizedEntryor the resolver hooks. - Confirm default-on vs opt-in startup matches policy,
allowedEventTypesmatches the pre-consent posture, and revoking consent blocks non-allowed events. - Confirm the first page event and route-change page events deliver, that one tracker is mounted per router tree, and that Strict Mode remounts do not duplicate them.
- Confirm baseline fallback renders when the Experience API fails, variants are missing, links are
unresolved, or a payload is all-locale — and that
OptimizedEntrystops showing loading after resolution settles or the 5-second reveal. - If you use managed fetching (
contentful: { client }with<OptimizedEntry entryId>), confirm a failed managed fetch renders yourerrorFallbackand reachesonEntryError, and that the managed query still uses one concrete locale with a deep enoughinclude. - Confirm
identifyUser(),setConsent(), andresetUser()re-resolve only the entries configured for live updates, and that reset runs when identity changes. - Confirm entry views, clicks, hovers, flag views, page events, and forwarded analytics deliver only
when policy permits, that forwarding dedupes by
messageId, and that manual element tracking clears overrides on unmount. - Confirm preview-panel code is environment-gated out of production bundles unless release policy allows it.
- Run the local validation path below.
Copy this:
Troubleshooting
Reference implementations to compare against
- React Web SDK reference implementation: Working
React SPA using
OptimizationRoot,ReactRouterAutoPageTracker,OptimizedEntry, the SDK-ready fetch pattern, live updates, merge tags, automatic and manual entry tracking, an event-stream display, consent and identity controls, and environment-gated preview-panel attachment. - Custom React adapter over the Web SDK: Builds a
custom React adapter on top of
@contentful/optimization-webfor comparison when an app needs full control instead of the official React Web SDK surface.