Skip to main content
Contentstack MCP profile hub is in general availability!

Track impressions and conversions

•
6 min read

The edge function picks variants. It cannot tell whether the visitor scrolled to the personalized banner or clicked its button. Without that data, an A/B test has no result and Multi-Armed Bandit has nothing to optimize. Tracking lives in the browser, and with the edge setup it costs almost nothing, because the browser already has the manifest in a cookie.

What you'll learn

  • How to initialize the SDK once in a Next.js client component

  • When to use triggerImpression() and when triggerImpressions()

  • How to derive impressions from the CDA response

  • How to send conversions and set attributes

  • What to do when an anonymous visitor logs in

Events and metrics

Personalize concept: An event is a named action with a key, such as signupClicked. You create it in the Personalize project.

There are two kinds of tracking calls:

  • Impressions say "this visitor saw variant X of experience Y". Personalize counts them once per visitor.

  • Conversions say "this visitor did the thing we care about". You send them with triggerEvent(eventKey).

An event becomes a metric when you add it to an A/B test experience. The first one you add is the primary metric, which decides the winner. An A/B test experience takes up to 10 metrics by default.

Initialize the SDK in the browser

Create a provider that initializes the SDK once per page load and shares the instance:

// components/personalize/PersonalizeProvider.tsx
'use client';

import { createContext, useContext, useEffect, useState } from 'react';
import Personalize from '@contentstack/personalize-edge-sdk';
import type { Sdk } from '@contentstack/personalize-edge-sdk/dist/sdk';

const PersonalizeContext = createContext<Sdk | null>(null);

let sdkPromise: Promise<Sdk> | null = null;

function getSdk() {
  if (!sdkPromise) {
    if (process.env.NEXT_PUBLIC_CONTENTSTACK_PERSONALIZE_EDGE_API_URL) {
      Personalize.setEdgeApiUrl(process.env.NEXT_PUBLIC_CONTENTSTACK_PERSONALIZE_EDGE_API_URL);
    }
    sdkPromise = Personalize.init(
      process.env.NEXT_PUBLIC_CONTENTSTACK_PERSONALIZE_PROJECT_UID as string
    );
  }
  return sdkPromise;
}

export function PersonalizeProvider({ children }: { children: React.ReactNode }) {
  const [sdk, setSdk] = useState<Sdk | null>(null);

  useEffect(() => {
    getSdk().then(setSdk).catch(() => setSdk(null));
  }, []);

  return <PersonalizeContext.Provider value={sdk}>{children}</PersonalizeContext.Provider>;
}

export const usePersonalize = () => useContext(PersonalizeContext);

Wrap {children} in app/layout.tsx with <PersonalizeProvider>.

In the browser, init() checks for the cs-personalize-manifest cookie. The edge function wrote it on this response, so the SDK reuses that manifest and the user UID cookie. The browser and the server agree on the variants because they read the same decision.

The project UID needs the NEXT_PUBLIC_ prefix to reach the browser bundle. It is not a secret; it identifies the project, the same way it does in the edge function.

Impressions for a known experience

When a component always renders one experience, fire an impression after it mounts:

'use client';

import { useEffect } from 'react';
import { usePersonalize } from '@/components/personalize/PersonalizeProvider';

export function HeroImpression({ experienceShortUid }: { experienceShortUid: string }) {
  const sdk = usePersonalize();

  useEffect(() => {
    if (!sdk) return;
    sdk.triggerImpression(experienceShortUid).catch(console.error);
  }, [sdk, experienceShortUid]);

  return null;
}

triggerImpression() looks up the active variant for that experience in the manifest and reports it. You find the experience short UID on the Experiences list in Personalize.

The catch is that this hard-codes an experience short UID in your code. Every new experience needs a code change.

Impressions from the CDA response

The better approach reads the applied variants from the content itself. Each entry in a CDA response carries publish_details.variants, and each value has an alias:

{
  "title": "Spring pricing",
  "publish_details": {
    "variants": {
      "cs3f1c9a2b7d4e5f60": { "alias": "cs_personalize_a_0" },
      "cs8e7d6c5b4a392817": { "alias": "cs_personalize_b_1" }
    }
  }
}

Pass the aliases from the server component to a small client component:

// lib/personalize.ts
type WithVariants = {
  publish_details?: { variants?: Record<string, { alias: string }> };
};

export function appliedAliases(entry: WithVariants): string[] {
  return Object.values(entry.publish_details?.variants ?? {}).map((v) => v.alias);
}
'use client';

import { useEffect } from 'react';
import { usePersonalize } from '@/components/personalize/PersonalizeProvider';

export function VariantImpressions({ aliases }: { aliases: string[] }) {
  const sdk = usePersonalize();
  const key = aliases.join(',');

  useEffect(() => {
    if (!sdk || !key) return;
    sdk.triggerImpressions({ aliases: key.split(',') }).catch(console.error);
  }, [sdk, key]);

  return null;
}

Render <VariantImpressions aliases={appliedAliases(page)} /> next to the personalized content. With aliases, triggerImpressions() takes the experience and variant from each alias and does not consult the manifest. A new experience on that content type starts reporting without a deploy.

This matters because the manifest says what a visitor should see, not what rendered. If an experience is active but nobody created an entry variant for this entry, the manifest still lists it, and a manifest-based impression would be a false one.

Limit to remember: publish_details.variants is per entry. If personalized items are modular blocks inside one entry, the attribution sits on the parent entry only. For lazy-loaded or below-the-fold items, fire the impression when the item enters the viewport, not on page load.

Conversions

Send a conversion when the visitor completes the action:

'use client';

import { usePersonalize } from '@/components/personalize/PersonalizeProvider';

export function SignupButton() {
  const sdk = usePersonalize();

  return (
    <button onClick={() => sdk?.triggerEvent('signupClicked').catch(console.error)}>
      Start free trial
    </button>
  );
}

The key must match an event in your project. Personalize attributes the conversion to the variants the visitor was assigned, so you do not pass the experience or variant.

Set attributes as you learn things

set() stores custom attributes for the visitor. They apply from the next manifest evaluation, which with this setup is the next page request:

await sdk.set({ plan: 'enterprise', newsletter: true });

Each key must exist as a custom attribute in the project. Setting a key again overwrites it.

When the visitor logs in

An anonymous visitor has a generated user UID. When they log in, switch to your own ID and keep what you learned:

await sdk.setUserId(account.id, { preserveUserAttributes: true });

preserveUserAttributes merges the attributes from the anonymous profile into the identified one.

Where people usually get confused

Confusion 1: Tracking from the server

Calling triggerImpression() in the edge function or a server component counts every cache miss, not every view. Keep tracking in client components.

Confusion 2: Impressions for segmented experiences

Impressions are optional for segmented experiences, but they are how you see reach per variant in analytics. For A/B tests they are required to measure anything.

Confusion 3: No numbers in analytics

Check three things: the event key matches exactly, the event is added as a metric on the experience, and the SDK initialized in the browser. The Network tab shows calls to the Edge API /events endpoint when tracking works.

Key takeaways

  • Initialize the browser SDK once; it reuses the cs-personalize-manifest cookie from the edge.

  • Prefer sdk.triggerImpressions({ aliases }) with aliases from publish_details.variants.

  • Fire impressions after the content renders, never from the server.

  • Send conversions with sdk.triggerEvent(eventKey) using keys that exist in the project.

  • On login, call sdk.setUserId(id, { preserveUserAttributes: true }).

Frequently asked questions

  • Why can't the edge function track impressions?

    The edge function knows which variants were selected, not what the visitor saw. Impressions and conversions belong in the browser, after the content renders.

  • Does the browser SDK fetch the manifest again?

    Not when the cs-personalize-manifest cookie is present. init() in the browser reads the manifest from the cookie set by the edge function.

  • Are repeated impressions counted twice?

    No. Personalize counts unique impressions per visitor, but avoid firing duplicates on the same page load anyway.

  • What is the primary metric?

    The first event added to an A/B test experience. It decides the winning variant; other metrics are secondary insights.