Do this with AI
Install the personalize and launch-platform skills from Contentstack agent skills. Then ask your agent:
Review my Launch edge function that calls the Personalize Edge SDK and check that it rewrites the URL with the variant parameter, sets the visitor cookie and skips static assets.
New to this? Set up your AI workbench first.
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:
npm install @contentstack/personalize-edge-sdkThe 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:
// 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:
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:
// 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 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.
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:
// 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).
Frequently asked questions
Which cookies does the Edge SDK set?
addStateToResponse() sets cs-personalize-user-uid with the visitor ID and cs-personalize-manifest with the current manifest.
Can I write the Launch Edge Function in TypeScript?
No. Launch Edge Functions are JavaScript only, so keep functions/[proxy].edge.js as a .js file.
What if the Personalize Edge API is unreachable?
init() throws. Catch it and forward the original request so visitors get the base page instead of an error.
Do I need setEdgeApiUrl()?
Only if your Personalize project is outside AWS North America. Call it with your region's Edge API URL before init().