---
title: "Personalize with server-side rendering at the edge"
url: "https://developers.contentstack.com/guides/personalize-with-ssr-at-the-edge"
type: "guide"
level: "advanced"
intent: "build"
outcome: "You can serve personalized, cacheable server-rendered pages where the edge picks the variants and the origin only renders them."
prerequisites:
  - "A Next.js App Router site that reads content from a Contentstack stack"
  - "A Personalize project connected to that stack"
  - "Hosting with an edge layer, such as Contentstack Launch Edge Functions"
  - "Working knowledge of the TypeScript Delivery SDK"
tags:
  - "personalization"
  - "sdk"
  - "next"
authors:
  - "Tim Benniks"
published: "2026-11-26T09:00:00.000Z"
updated: "2026-11-15T10:56:15.142Z"
---

# Personalize with server-side rendering at the edge

- **Authors:** Tim Benniks
- **Published:** 2026-11-26T09:00:00.000Z
- **Updated:** 2026-11-15T10:56:15.142Z
- **Level:** Advanced
- **Intent:** Build
- **Tags:** personalization, sdk, next
- **Chapters:** 5
- **Source:** [https://developers.contentstack.com/guides/personalize-with-ssr-at-the-edge](https://developers.contentstack.com/guides/personalize-with-ssr-at-the-edge)

---

## Table of Contents

1. [How Personalize resolves variants](#how-personalize-resolves-variants)
2. [Set up the Personalize Edge SDK](#set-up-the-personalize-edge-sdk)
3. [Fetch entry variants and cache them per variant](#fetch-entry-variants-and-cache-them-per-variant)
4. [Track impressions and conversions](#track-impressions-and-conversions)
5. [Layered and prioritized experiences](#layered-and-prioritized-experiences)

Personalization usually breaks one of three things: page speed, caching or SEO. Run it in the browser and you get a flash of default content before the variant appears. Run it on the origin for every request and you lose your CDN cache. Personalize avoids both if you split the work: an edge function decides which variants a visitor gets, and the origin renders those variants as if they were normal content.

This guide builds that setup on Next.js and Contentstack Launch. The same split works on Vercel, Netlify, Cloudflare Workers and other edge runtimes, and the guide calls out where they differ.

## What you'll learn

- How Personalize turns a visitor into a set of variant aliases


- How to run the Personalize Edge SDK in a Launch Edge Function


- How to fetch entry variants with the Delivery SDK and cache the result per variant


- How to track impressions and conversions from the browser


- How priority decides what renders when experiences overlap



## How the pieces fit

Every page request goes through the same path. The edge function asks the Personalize Edge API for the visitor's manifest, writes the active variants into a query parameter, and forwards the request. The CDN treats that rewritten URL as the cache key. On a miss, the origin reads the parameter, asks the Content Delivery API (CDA) for the matching entry variants and renders HTML.

sequenceDiagram    participant B as Browser    participant E as Edge function    participant P as Personalize Edge API    participant C as CDN cache    participant O as Next.js origin    participant D as Content Delivery API    B->>E: GET /pricing (cookies)    E->>P: Fetch manifest for this visitor    P-->>E: Active variant per experience    E->>C: GET /pricing?personalize_variants=a_0,b_1    alt cache hit        C-->>E: Cached personalized HTML    else cache miss        C->>O: Forward request        O->>D: Fetch entries with variant aliases        D-->>O: Merged entry variants        O-->>C: HTML plus s-maxage        C-->>E: Personalized HTML    end    E-->>B: HTML plus Personalize cookies    B->>P: Impressions and conversionsThe origin never sees a user ID or an audience. It only sees a_0,b_1, which is why the response is safe to cache and share with every visitor who resolved to the same variants.

## The chapters

Each chapter covers one part of the flow:

- [How Personalize resolves variants](/guides/personalize-with-ssr-at-the-edge/how-personalize-resolves-variants) explains projects, attributes, audiences, experiences and how a variant alias maps to a CMS entry variant. Read it first if Personalize is new to you.


- [Set up the Edge SDK](/guides/personalize-with-ssr-at-the-edge/set-up-the-edge-sdk) builds the Launch Edge Function: initialize the SDK with the request, rewrite the URL, and write the user and manifest cookies.


- [Fetch entry variants](/guides/personalize-with-ssr-at-the-edge/fetch-entry-variants) reads the parameter on the origin, passes aliases to variants(), and sets cache headers that work when the response varies per variant.


- [Track impressions and conversions](/guides/personalize-with-ssr-at-the-edge/track-impressions-and-conversions) wires up the browser SDK so A/B tests and analytics have data.


- [Layered and prioritized experiences](/guides/personalize-with-ssr-at-the-edge/layered-and-prioritized-experiences) covers several experiences on one page, priority, and when to pick segmented versus A/B.



Production note: The code uses the instance API of @contentstack/personalize-edge-sdk (version 1.0.9 and later), where Personalize.init() returns an SDK instance. The older global methods such as Personalize.getVariantAliases() still exist but are deprecated, and they share state across requests at the edge.

If you are still deciding whether edge rendering is right for your project, read [Client, static, server or edge? Choosing a Personalize architecture](/blog/client-static-server-or-edge-choosing-a-personalize-architecture) first. For how Personalize relates to the CMS and Lytics, see [Understanding how Contentstack CMS, Personalize and Lytics work together](/blog/understanding-how-contentstack-cms-personalize-and-lytics-work-together).

## Key takeaways

- The edge function decides, the origin renders, the browser reports.


- Variants travel as a query parameter (personalize_variants), so the CDN caches one page per variant combination.


- The origin needs no Personalize credentials and no user context.


- On Launch, use an Edge Function in functions/[proxy].edge.js, not Next.js middleware.


- Use the SDK instance returned by Personalize.init(), not the deprecated global methods.





---

## How Personalize resolves variants

Before you write an edge function, you need to know what it is asking for. Personalize has its own vocabulary, and half of it shows up in the CMS under different names. Once you know which object lives where, the code in the next chapters reads like plumbing.

## What you'll learn

- What a Personalize project, attribute, audience, experience and variant are


- How the CMS mirrors experiences as variant groups


- What the user manifest contains


- How a variant alias maps to an entry variant


- Where people usually get confused



## The object model

### Project

Personalize concept: A project is the container for everything in Personalize, connected to one stack.

You need the 24-character project UID to initialize the SDK. Find it in Personalize under Settings, General, Project Details.

### Attributes

Personalize concept: Attributes are key-value pairs that describe a visitor.

There are two kinds:

- Preset attributes come for free: city, country, region, date and time, device type, operating system, query parameter and referrer. The Edge API derives them from the request.


- Custom attributes are ones you create in the project, such as plan or age. Your code sets them with the SDK set() method, or as live attributes at initialization.



### Audiences

Personalize concept: An audience is a set of rules over attributes, combined with Match All or Match Any.

country = US and device = mobile with Match All is an audience. Personalize audiences are evaluated at the edge on each request and are not stored. Lytics audiences are the other kind: built from unified customer profiles in Lytics and passed to Personalize.

### Experiences

Personalize concept: An experience is the decision. It holds variants and the rules for picking one.

There are two types:

- Segmented: each variant targets one or more audiences. The first variant in the list whose conditions match wins.


- A/B test: traffic is split across variants (equal, custom split, or Multi-Armed Bandit). The target group decides who enters the test: everyone by default, or only selected audiences.



A visitor has at most one active variant per experience.

### Variants

Personalize concept: A variant is one outcome of an experience, such as "EU shoppers" or "Variant B".

Each experience and each variant has a short UID, such as a and 0. Short UIDs keep URLs and cookies small, and you will see them everywhere in the SDK.

## How the CMS mirrors experiences

When a Personalize project is connected to a stack, the two stay in sync:

Personalize

CMS

Experience

Variant group (same name)

Variant

Variant inside that group

Nothing

Entry variant: the field overrides for one entry and one variant

A variant group only shows up in the entry editor after you link it to content types. Then an editor picks a variant in the entry and changes fields. The first change creates the entry variant.

Contentstack concept: Entry variants are diffs. They store only the fields that differ from the base entry, and the CDA merges base and overrides at read time. When an editor fixes a typo in the base entry, every variant that did not override that field gets the fix.

If you are coming from Git, think of the base entry as main and each entry variant as a small patch that is applied on read, never merged.

Entry variants are published like entries. Activate the experience in Personalize and publish the entry variants to your environment, or the CDA has nothing to return.

## The user manifest

When the Edge SDK initializes, it calls the Personalize Edge API, which evaluates every active experience for this visitor and returns the manifest:

```json
{
  "experiences": [
    { "shortUid": "a", "activeVariantShortUid": "0" },
    { "shortUid": "b", "activeVariantShortUid": "1" },
    { "shortUid": "c", "activeVariantShortUid": null }
  ]
}
```

The list is sorted by experience priority, highest first. Experience c had no matching variant, so it is null.

## From manifest to alias

The SDK turns the manifest into three shapes. You use each one in a different place:

SDK method

Value

Used by

sdk.getVariants()

{ a: '0', b: '1' }

Your own logic

sdk.getVariantParam()

'a_0,b_1'

The URL, from the edge function

sdk.getVariantAliases()

['cs_personalize_a_0', 'cs_personalize_b_1']

The Delivery SDK

getVariantParam() and getVariantAliases() skip experiences without an active variant. On the origin, the static helper Personalize.variantParamToVariantAliases('a_0,b_1') turns the URL value back into aliases without initializing the SDK.

The alias is the contract between Personalize and the CMS. cs_personalize_a_0 means "experience a, variant 0", and the CDA knows which entry variant that is.

flowchart LR    V[Visitor request] --> M[Manifest: a=0, b=1]    M --> P["URL param: a_0,b_1"]    P --> A["Aliases: cs_personalize_a_0, cs_personalize_b_1"]    A --> D[CDA merges base entry with overrides]    D --> H[Rendered HTML]## Where people usually get confused

### Confusion 1: "Variant" means two things

In Personalize, a variant is an outcome of an experience. In the CMS, a variant is the same thing, but the content lives in an entry variant per entry. A variant with no entry variant on a given entry renders the base entry for that entry.

### Confusion 2: Audiences do not decide content directly

An audience only matters when an experience's variant targets it. Creating an audience changes nothing on the site.

### Confusion 3: The manifest is not the content

The manifest says which variant a visitor should see. It does not prove that an entry variant exists or was rendered. That matters for impression tracking in [chapter 4](/guides/personalize-with-ssr-at-the-edge/track-impressions-and-conversions).

### Confusion 4: Personalize audiences are not analytics

Personalize audience membership is computed per request and thrown away. If you need audience reporting or cross-channel profiles, that is a Lytics job.

## Limits to remember

The default plan limits per project are:

- 100 experiences, 100 audiences, 100 custom attributes and 100 events


- 50 rules per audience


- 20 variants per experience


- 10 metrics per A/B test experience



Support can raise each of these. The Personalize Edge API has no published rate limit; the Management API is limited to 10 requests per second per organization.

## Key takeaways

- A visitor resolves to at most one variant per experience.


- Experiences map to variant groups in the CMS; link the group to content types before editors can create entry variants.


- Entry variants store only overridden fields and are merged by the CDA at read time.


- The alias format is cs_personalize_<experience>_<variant>, and the URL form is <experience>_<variant>.


- The manifest is sorted by priority, which becomes important when experiences overlap.





---

## Set up the Personalize Edge SDK

The edge function is the only place where Personalize makes a decision. It runs before the CDN cache, knows who the visitor is from their cookies, and has the full request for geolocation, referrer and query parameters. Its job is small: get the manifest, put the variants in the URL, forward the request, and remember the visitor.

## What you'll learn

- Why a Launch Edge Function and not Next.js middleware


- How to initialize the SDK with the incoming request


- How to rewrite the URL with the variant parameter


- What the two Personalize cookies do


- How to fail safe and skip asset requests



## Install the SDK

Install the package in your Next.js project:

```bash
npm install @contentstack/personalize-edge-sdk
```

The edge function, the origin and the browser code all import this one package.

## Pick the right edge layer

Launch note: On Launch, Next.js middleware runs on the server, not at the edge. It runs after the CDN cache, which defeats the purpose. Use a Launch Edge Function instead: a file at functions/[proxy].edge.js that runs in front of every request.

On Vercel, Next.js middleware does run at the edge, so the same logic goes in middleware.ts. That version is at the end of this chapter.

Launch Edge Functions have a few constraints:

- JavaScript only, no TypeScript


- A WinterCG runtime, so no Node.js APIs such as fs


- 128 MB memory, a 1 MiB minified bundle, and 400 ms for global-scope startup


- Environment variables come from context.env, not process.env



## Start with a pass-through

Create the function and confirm it proxies everything before adding logic:

```javascript
// functions/[proxy].edge.js
export default async function handler(request, context) {
  return fetch(request);
}
```

fetch(request) forwards the request to the CDN and origin. Deploy and click through the site. If anything breaks here, it is not Personalize.

## Initialize the SDK with the request

Pass the incoming Request to init(). The SDK reads the visitor's cookies from it, extracts preset attributes such as referrer, query parameters and geolocation, and fetches the manifest from the Edge API:

```javascript
import Personalize from '@contentstack/personalize-edge-sdk';

export default async function handler(request, context) {
  if (context.env.CONTENTSTACK_PERSONALIZE_EDGE_API_URL) {
    Personalize.setEdgeApiUrl(context.env.CONTENTSTACK_PERSONALIZE_EDGE_API_URL);
  }

  const sdk = await Personalize.init(
    context.env.NEXT_PUBLIC_CONTENTSTACK_PERSONALIZE_PROJECT_UID,
    { request }
  );

  return fetch(request);
}
```

init() returns an SDK instance scoped to this request. Use the instance methods (sdk.getVariantParam(), sdk.addStateToResponse()). The global equivalents are deprecated because module-level state leaks between concurrent requests in an edge runtime.

setEdgeApiUrl() is only needed outside AWS North America. The Edge API URLs per region are:

Region

Edge API URL

AWS NA

https://personalize-edge.contentstack.com

AWS EU

https://eu-personalize-edge.contentstack.com

AWS AU

https://au-personalize-edge.contentstack.com

Azure NA

https://azure-na-personalize-edge.contentstack.com

Azure EU

https://azure-eu-personalize-edge.contentstack.com

GCP NA

https://gcp-na-personalize-edge.contentstack.com

## The full edge function

Here is the complete function. It skips assets, resolves variants, rewrites the URL, writes cookies, and falls back to the base page if anything fails:

```javascript
// functions/[proxy].edge.js
import Personalize from '@contentstack/personalize-edge-sdk';

const SKIP = ['/_next/', '/api/', '/favicon.ico'];

export default async function handler(request, context) {
  const url = new URL(request.url);

  if (SKIP.some((prefix) => url.pathname.startsWith(prefix))) {
    return fetch(request);
  }

  if (context.env.CONTENTSTACK_PERSONALIZE_EDGE_API_URL) {
    Personalize.setEdgeApiUrl(context.env.CONTENTSTACK_PERSONALIZE_EDGE_API_URL);
  }

  let sdk;
  try {
    sdk = await Personalize.init(
      context.env.NEXT_PUBLIC_CONTENTSTACK_PERSONALIZE_PROJECT_UID,
      { request }
    );
  } catch (error) {
    console.error('Personalize init failed', error);
    return fetch(request);
  }

  // Never trust a variant param sent by the client
  url.searchParams.delete(sdk.VARIANT_QUERY_PARAM);
  const variantParam = sdk.getVariantParam();
  if (variantParam) {
    url.searchParams.set(sdk.VARIANT_QUERY_PARAM, variantParam);
  }

  const originResponse = await fetch(new Request(url.toString(), request));
  const response = new Response(originResponse.body, originResponse);

  sdk.addStateToResponse(response);
  response.headers.set('cache-control', 'no-store');

  return response;
}
```

A few lines here deserve an explanation.

The rewrite is invisible. The visitor's address bar still shows /pricing. Only the request to the CDN and origin carries /pricing?personalize_variants=a_0,b_1.

Delete before set. If someone shares a URL that already contains personalize_variants, the edge function replaces it with the real decision. That keeps visitors in their own variants and keeps junk combinations out of your cache.

Skip the empty parameter. Visitors with no active variants request the plain URL, so they all share one cached base page instead of a separate ?personalize_variants= entry.

Fail safe. If the Edge API call fails, init() throws. Catching it and forwarding the original request means an outage costs you personalization, not the site.

## What the cookies do

addStateToResponse() appends two Set-Cookie headers to the response:

Cookie

Contents

Why it matters

cs-personalize-user-uid

The visitor's user UID

The Edge API recognizes the visitor on the next request, so A/B assignments and stored attributes stick

cs-personalize-manifest

The current manifest as JSON

The browser SDK can initialize from this cookie without another manifest call

Both cookies are written with Secure and SameSite=Lax. The first request from a new visitor has no user UID cookie, so the Edge API generates one and addStateToResponse() persists it.

The cookies are added after the CDN returns the page, so they never end up in a cached response. That is the reason to add them in the edge function and not in the origin.

cache-control: no-store on the final response stops the browser from caching this personalized HTML. The CDN cache in front of the origin is controlled separately, by the origin's own headers. [Chapter 3](/guides/personalize-with-ssr-at-the-edge/fetch-entry-variants) sets those.

## Passing your own context

init() accepts more options when the request alone is not enough:

- liveAttributes: custom attributes for this request only, evaluated immediately and not persisted. Useful when the edge already knows something, such as a plan tier from a signed cookie.


- userId: use your own user ID instead of the generated one.


- tags: evaluate only experiences that carry at least one of these tags (up to 10). See [chapter 5](/guides/personalize-with-ssr-at-the-edge/layered-and-prioritized-experiences).



```javascript
const sdk = await Personalize.init(projectUid, {
  request,
  liveAttributes: { plan: readPlanFromCookie(request) },
});
```

Live attributes must match custom attributes that exist in your Personalize project.

## The same flow in Next.js middleware

On hosts where Next.js middleware runs at the edge, such as Vercel, the logic moves to middleware.ts:

```typescript
// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
import Personalize from '@contentstack/personalize-edge-sdk';

export const config = {
  matcher: ['/((?!_next/|api/|favicon.ico).*)'],
};

export default async function middleware(request: NextRequest) {
  if (process.env.CONTENTSTACK_PERSONALIZE_EDGE_API_URL) {
    Personalize.setEdgeApiUrl(process.env.CONTENTSTACK_PERSONALIZE_EDGE_API_URL);
  }

  const sdk = await Personalize.init(
    process.env.NEXT_PUBLIC_CONTENTSTACK_PERSONALIZE_PROJECT_UID as string,
    { request }
  );

  const url = request.nextUrl.clone();
  url.searchParams.delete(sdk.VARIANT_QUERY_PARAM);
  const variantParam = sdk.getVariantParam();
  if (variantParam) url.searchParams.set(sdk.VARIANT_QUERY_PARAM, variantParam);

  const response = NextResponse.rewrite(url);
  sdk.addStateToResponse(response);
  return response;
}
```

NextResponse.rewrite() replaces the explicit fetch(), and the matcher replaces the skip list. Everything else is the same.

## Key takeaways

- On Launch, use functions/[proxy].edge.js; Next.js middleware there runs on the server.


- Call Personalize.init(projectUid, { request }) and use the returned instance.


- Delete any incoming personalize_variants and set it only when getVariantParam() is not empty.


- Call sdk.addStateToResponse(response) in the edge function so cookies never reach the CDN cache.


- Wrap init() in try/catch and fall back to fetch(request).





---

## Fetch entry variants and cache them per variant

The origin's job in this setup is boring on purpose. It reads one query parameter, turns it into aliases, and passes them to every Delivery SDK call that returns personalized content. It knows nothing about the visitor. That is what makes the response cacheable.

## What you'll learn

- How to read the variant parameter in a Next.js App Router page


- How to pass aliases to variants() on single entries and queries


- How the CDA merges several variants into one entry


- Which cache headers to send from the origin on Launch


- What breaks caching and how to avoid it



## Read the parameter on the origin

In the App Router, searchParams holds the rewritten query string. Convert the value with the static helper Personalize.variantParamToVariantAliases(). It does not need an initialized SDK and makes no network call:

```typescript
// app/[[...slug]]/page.tsx
import Personalize from '@contentstack/personalize-edge-sdk';
import { notFound } from 'next/navigation';
import { getPageByUrl } from '@/lib/contentstack';
import { PageRenderer } from '@/components/PageRenderer';

type Props = {
  params: Promise<{ slug?: string[] }>;
  searchParams: Promise<Record<string, string | undefined>>;
};

export default async function Page({ params, searchParams }: Props) {
  const { slug } = await params;
  const query = await searchParams;

  const variantParam = query[Personalize.VARIANT_QUERY_PARAM];
  const aliases = variantParam
    ? Personalize.variantParamToVariantAliases(variantParam)
    : [];

  const page = await getPageByUrl(`/${slug?.join('/') ?? ''}`, aliases);
  if (!page) notFound();

  return <PageRenderer page={page} />;
}
```

Personalize.VARIANT_QUERY_PARAM is personalize_variants unless you passed customVariantQueryParam to init() at the edge. If you did, read that name here instead.

Reading searchParams makes the route dynamic, which is what you want: the origin renders per variant combination, and the CDN does the caching.

## Pass aliases to the Delivery SDK

variants() accepts a string or an array of aliases. Call it before query(), find() or fetch():

```typescript
// lib/contentstack.ts
import contentstack from '@contentstack/delivery-sdk';
import type { Page } from '@/types/contentstack';

const stack = contentstack.stack({
  apiKey: process.env.CONTENTSTACK_API_KEY as string,
  deliveryToken: process.env.CONTENTSTACK_DELIVERY_TOKEN as string,
  environment: process.env.CONTENTSTACK_ENVIRONMENT as string,
});

export async function getPageByUrl(url: string, aliases: string[]) {
  let entries = stack.contentType('page').entry();
  if (aliases.length) entries = entries.variants(aliases);

  const result = await entries
    .includeReference('sections.cta')
    .query()
    .equalTo('url', url)
    .find<Page>();

  return result.entries?.[0];
}
```

For a single entry by UID, the chain is the same with fetch():

```typescript
const banner = await stack
  .contentType('banner')
  .entry('blt0123456789abcdef')
  .variants(aliases)
  .fetch();
```

Under the hood, the SDK sends the aliases as a comma-separated x-cs-variant-uid header. Without the header, the CDA returns base entries.

Production note: Pass the aliases to every request that returns personalized entries, including separate calls for headers, footers or listing pages. Each request carries its own header, and a call without it gets base content.

## How the CDA merges variants

You can pass all of the visitor's aliases to every call, even if most do not apply to that content type. For each entry, the CDA:

- Starts from the base entry.


- Applies the overrides of each matching entry variant.


- Leaves fields that no variant overrides untouched.


- Returns one merged entry.



If two variants override the same field on the same entry, the alias listed first wins. getVariantParam() lists experiences in priority order, highest first, so the higher-priority experience wins without any code from you. [Chapter 5](/guides/personalize-with-ssr-at-the-edge/layered-and-prioritized-experiences) covers this in detail.

Do not sort or deduplicate the aliases yourself. Their order is the priority.

## Set cache headers on the origin

The edge function sets no-store on what the browser receives. The origin decides what the CDN keeps. On Launch, set the header in next.config.js:

```javascript
// next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: '/:path*',
        headers: [
          {
            key: 'cache-control',
            value: 'max-age=0, s-maxage=86400, must-revalidate',
          },
        ],
      },
    ];
  },
};
```

s-maxage lets the CDN keep the page for a day. max-age=0 keeps it out of the browser cache. The Launch docs use stale-while-revalidate for regular pages; the Personalize setup swaps it for must-revalidate, so a visitor never gets an outdated variant while a refresh runs in the background. Scope the source pattern to your personalized routes if other routes need different rules.

The cache key on Launch is scheme, host, path and query string. /pricing?personalize_variants=a_0 and /pricing?personalize_variants=a_1 are two entries. Custom request headers are not part of the key, which is why the edge function puts variants in the URL and not in a header.

## What breaks caching

### Anything user-specific in the HTML

If the origin renders a visitor's name, cart count or user ID, the CDN serves it to the next visitor with the same variants. Keep the server render a function of path plus variants. Load the rest client-side.

### Too many combinations

Each combination of active variants is a separate cache entry per URL. Five experiences with three variants each can produce hundreds of combinations, and each one needs its own origin render to warm up. Only experiences that are active and matched for the visitor appear in the parameter, which helps. If experiences only apply to one section of the site, scope them with tags at the edge so other pages do not fragment.

### Your own data cache

If you wrap Delivery SDK calls in your own cache, such as unstable_cache, an in-memory map or a KV store, include the aliases in the cache key. Otherwise the first visitor's variant becomes everybody's.

### Stale variants after publishing

When an editor publishes an entry variant, cached pages for that combination are still the old version until s-maxage expires or you revalidate. For the options on Launch, see [Revalidate, prime or redeploy? Picking the right cache lever on Launch](/blog/revalidate-prime-or-redeploy-picking-the-right-cache-lever-on-launch) and the chapter on [caching, revalidation and cache priming](/guides/launch-edge-functions-redirects-and-caching/caching-revalidation-and-cache-priming).

## Live Preview

Live Preview works with Personalize projects through the TypeScript Delivery SDK's Live Preview setup. Preview requests carry draft content, so keep them out of the CDN cache: send no-store when a request has Live Preview parameters.

## Key takeaways

- Convert the URL value with Personalize.variantParamToVariantAliases(); the origin never calls the Edge API.


- Call .variants(aliases) on entry() or entry(uid) for every personalized request.


- Keep the alias order. The first alias wins a field conflict, and the SDK orders by priority.


- On Launch, send max-age=0, s-maxage=86400, must-revalidate from personalized routes.


- Keep server HTML a function of path and variants only; anything user-specific loads client-side.





---

## Track impressions and conversions

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:

```tsx
// 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:

```tsx
'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:

```json
{
  "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:

```typescript
// 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);
}
```

```tsx
'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:

```tsx
'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:

```typescript
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:

```typescript
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 }).





---

## Layered and prioritized experiences

A real visitor fits more than one bucket. They came from a spring campaign, they are on a phone, and they are in Germany. Personalize lets each of those facts drive its own experience, and the edge setup from this guide already supports that: the manifest lists every active experience, and the CDA layers every matching entry variant. What you need to control is what happens when two of them want the same field.

## What you'll learn

- How priority works inside one experience and across experiences


- How layering resolves on the CDA


- When to pick a segmented experience and when an A/B test


- How to scope experiences with tags


- Design rules that avoid conflicts



## Two kinds of priority

There are two separate orders, and people mix them up.

Variant priority lives inside a segmented experience. When a visitor matches the audiences of several variants, the first one in the experience's variant list wins. You reorder variants by dragging them in the experience configuration. Put the most specific audience first: "VIP customers" above "Visitors from the UK", or the VIP variant never shows for UK VIPs.

Experience priority lives across experiences in a project. By default, experiences are ordered by creation date, newest at the bottom. You change the order with Prioritize Experiences in Personalize. The experience at the top wins when two experiences touch the same content.

## How layering resolves

Take two active experiences on the pricing page:

Experience

Short UID

Priority

Changes on the pricing_page entry

Spring campaign

a

1

hero_title, hero_image

EU visitors

b

2

hero_title, currency_note

A visitor from Germany who arrived from the campaign gets the manifest a=0, b=0. The edge function sends personalize_variants=a_0,b_0, and the origin passes ['cs_personalize_a_0', 'cs_personalize_b_0'] to variants().

The CDA merges per field:

- hero_title: both override it. The first alias wins, so the visitor sees the campaign title.


- hero_image: only the campaign overrides it.


- currency_note: only the EU experience overrides it.


- Every other field comes from the base entry.



flowchart TB    B[Base entry] --> M{Merge per field}    A0["cs_personalize_a_0 (priority 1)"] --> M    B0["cs_personalize_b_0 (priority 2)"] --> M    M --> T["hero_title from a_0"]    M --> I["hero_image from a_0"]    M --> C["currency_note from b_0"]    M --> R[All other fields from base]The result is one entry that reflects both facts about the visitor. When experiences target different sections or different entries, there is no conflict at all, and each section shows its own variant.

Production note: The order of aliases is the priority. The SDK returns them sorted, highest priority first. If you build aliases yourself, for example from a non-JavaScript origin calling the Edge API directly, keep the manifest order.

## Segmented or A/B test

Both experience types produce the same aliases and use the same delivery code. The difference is how the variant gets picked and what you learn from it.


Segmented

A/B test

Picks the variant by

First matching audience, in variant order

Traffic split among visitors in the target group

Answers

"Show EU visitors the EU offer"

"Does headline B convert better than A?"

Needs metrics

No, impressions are optional

Yes, at least a primary metric

Traffic options

Not applicable

Equal split, custom split, Multi-Armed Bandit

Use segmented when you already know what each group should see. Use an A/B test when you do not know and want data. A common pattern is both: an A/B test inside one audience, such as testing two hero headlines only for returning visitors, by setting that audience as the test's target group (Selective) instead of Everyone.

A/B assignment sticks to the user UID for the duration of the test. A returning visitor with the same cs-personalize-user-uid cookie keeps their variant. If the cookie is cleared, they can land in a different variant, which is one more reason to persist the cookie with addStateToResponse() at the edge.

Custom split is useful for soft launches: send 20 percent of traffic to a redesigned page and keep 80 percent on the current one. Multi-Armed Bandit starts equal and shifts traffic toward the better-converting variant while the test runs, while every variant keeps a minimum share.

## Scope experiences with tags

Every experience the edge evaluates can add a variant to the URL, and every combination is a separate cache entry. If your checkout experiences have nothing to do with the blog, there is no reason to evaluate them on blog pages.

Tag experiences in Personalize, for example section:checkout or section:marketing, and pass the tags at initialization:

```javascript
const section = url.pathname.startsWith('/checkout') ? 'section:checkout' : 'section:marketing';

const sdk = await Personalize.init(context.env.NEXT_PUBLIC_CONTENTSTACK_PERSONALIZE_PROJECT_UID, {
  request,
  tags: [section],
});
```

Only experiences with at least one matching tag are returned. Matching is case-insensitive, and you can pass up to 10 tags. Without tags, the edge evaluates every eligible experience.

Tags also work for environments. Tag test experiences env:staging and production ones env:production, and initialize with the tag for the current deployment, instead of keeping a separate Personalize project per environment.

## Design rules that keep layering predictable

- Give each experience a job. One experience per decision, such as "campaign hero" or "regional pricing note". Avoid two experiences that both rewrite the whole page.


- Overlap on purpose. If two experiences must touch the same field, decide the priority before activating, not after a stakeholder sees the wrong headline.


- Keep A/B tests away from contested fields. If a higher-priority segmented experience overrides the field under test, part of your test traffic never sees the tested variant, and the result is skewed.


- Watch the cache. Each added experience multiplies the possible variant combinations. Tags and fewer, broader experiences keep hit rates up.



## Where people usually get confused

### Confusion 1: Experience priority does not pick variants

Experience priority only matters when two experiences override the same field. It does not stop a lower-priority experience from being active.

### Confusion 2: Reordering is live

Changing experience priority changes what visitors see on the next manifest. Pages already in the CDN cache keep the old merge until they expire or you revalidate.

### Confusion 3: "No variant" is a valid result

A segmented experience where no audience matches returns null for that visitor. The experience adds nothing to the URL and the base content renders. That is expected, not a bug.

## Key takeaways

- Inside a segmented experience, the first matching variant wins; order variants from specific to general.


- Across experiences, the top of Prioritize Experiences wins field conflicts on the same entry.


- The first alias wins a field conflict on the CDA, so keep the SDK's alias order intact.


- Use segmented when you know the answer and A/B tests when you need one.


- Pass tags to Personalize.init() to keep unrelated experiences out of the manifest and the cache key.





---

## Do this with AI

Install the personalize and cms-variants-personalization skills from [Contentstack agent skills](https://github.com/contentstack/contentstack-agent-skills) and connect the Personalization Strategist profile in MCP Profile Hub. Then ask your agent:

> List the active experiences in my Personalize project with their type, priority and variant aliases, and map each alias to the CMS entry variants it should load.

New to this? [Set up your AI workbench](/guides/set-up-your-ai-workbench-for-contentstack) first.




---

## Frequently asked questions

### Why resolve variants at the edge instead of in the browser?

The page arrives already personalized, so there is no flicker, search engines see real HTML, and the CDN can cache one copy per variant combination.

### Does my origin need the Personalize SDK?

Only for one static helper that turns the variant query parameter into aliases. The origin never calls the Personalize Edge API.

### Can I use Next.js middleware on Launch for this?

No. On Launch, Next.js middleware runs on the server, not at the edge, so use a Launch Edge Function instead.

### Where do impressions and conversions get tracked?

In the browser. The edge function picks variants; the browser SDK reports what the visitor saw and did.

