XeniaXenia Docs

Edge personalization

PreviousNext

Personalize server-rendered pages from your own proxy, with one cached Xenia call per visitor and page and base content on any failure.

Edge personalization is for a site that renders pages on its own server or edge, for example Next.js, a storefront proxy, or a server in front of your CMS. Your proxy knows which pages a journey targets and asks Xenia only for those, within a hard time budget. Each visitor's decision is cached for the session. A timeout, an error, or a missing manifest all serve base content, so Xenia can never slow down or break a page.

It serves journeys whose Personalization Trigger has Server-side pull channel only switched on. With the switch off, use resolve() instead. See Which integration does my journey need?

How it works

  1. Xenia publishes a manifest: which content keys target which pages. Pages come from the Pages list on the journey's Personalization Trigger, for example /, /women/* or uk.example.com/sale.
  2. On each page request, your proxy checks the path against the manifest. A page no journey targets never calls Xenia.
  3. For a targeted page, the proxy asks Xenia to decide for this visitor (about 150 ms budget), then caches the answer for the visitor and page.
  4. The proxy rewrites to a variant page. The variant is a signed token that holds only the swaps, so every visitor in the same variant shares one cached render.

Next.js

@xenia-martech/sdk-js/next runs the whole flow in one call. It skips bots and non-GET requests, sets the visitor cookie, reads consent, builds the standard facts, calls Xenia, rewrites to the variant page and adds a Server-Timing header.

// proxy.ts
import type { NextRequest } from "next/server";
import { createXeniaEdge } from "@xenia-martech/sdk-js/edge";
import { xeniaEdgeProxy } from "@xenia-martech/sdk-js/next";
 
const edge = createXeniaEdge({
  token: process.env.XENIA_SDK_TOKEN!,
  manifestUrl: `${process.env.URL}/api/xenia/manifest`, // your own copy, below
});
// Or from XENIA_SDK_TOKEN, XENIA_URL, XENIA_EDGE_BUDGET_MS and XENIA_MANIFEST_URL:
// const edge = xeniaEdgeFromEnv();
 
export const proxy = (request: NextRequest) =>
  xeniaEdgeProxy(request, {
    edge,
    variantSecret: process.env.XENIA_VARIANT_SECRET!, // the variant page verifies with it
    skip: (path) => path.startsWith("/account"),       // pages with no variant page
    facts: (ctx) => ({ signed_in: Boolean(ctx.request.cookies.get("session")) }),
  });

Two route factories serve the manifest and keep it fresh:

// app/api/xenia/manifest/route.ts
import { createManifestRoute } from "@xenia-martech/sdk-js/next";
 
export const revalidate = 300;
export const GET = createManifestRoute({ token: process.env.XENIA_SDK_TOKEN, revalidate });
// app/api/xenia/revalidate/route.ts — Xenia's storefront webhook
import { createRevalidateRoute } from "@xenia-martech/sdk-js/next";
 
export const POST = createRevalidateRoute({
  secret: process.env.XENIA_WEBHOOK_SECRET!,
  paths: ["/api/xenia/manifest"],
});

The webhook regenerates your manifest the moment a journey changes. Point manifestUrl at that route: its copy lists pages rather than content keys, so a journey published since the last refresh is still decided.

To bundle the manifest at build time, add xenia-manifest public/xenia-manifest.json as a prebuild script and pass the file as initialManifest. A cold instance then never waits for it, and an unreachable Xenia never fails the build.

Hooks

HookUse it for
skip(path)Pages that have no variant page. Their views still count towards the trail.
prepare(ctx)Changing the visitor, location or trail first, for example a profile switch
facts(ctx) / cacheFacts(ctx)Your own facts, and which of them should give a visitor a fresh decision
budgetMs(ctx)A bigger budget for a decision that calls one of your own systems
geoHeadersThe location headers your host sets. None are trusted by default.
filterDecisions, extra, rewriteDropping decisions, carrying data in the variant token, or rendering elsewhere
onDecision(info) / onError(error)Debug output and error reporting. The page is served either way.

The variant page

The page behind the rewrite reads the swaps back from the token with decodeVariant(token, secret). A token that is malformed or not signed with your secret returns null, so a crafted URL can never render arbitrary entries.

For a CMS page journey, personalizeVariantPage verifies the token, fetches the page and applies every level of swaps in one call, with no Xenia call:

// app/xv/[token]/[[...slug]]/page.tsx — cached per variant
import { personalizeVariantPage } from "@xenia-martech/sdk-js/edge";
 
export const revalidate = 60;
export async function generateStaticParams() { return []; }
 
export default async function Page({ params }) {
  const { token, slug } = await params;
  const { content } = await personalizeVariantPage(token, { contentType: "page", fields: { slug } }, {
    secret: process.env.XENIA_VARIANT_SECRET!,
    cms,                     // contentfulAdapter or contentstackAdapter
    contentKey: "home-main", // omit to apply every journey the token decided
  });
  if (!content) notFound();
  return <PageView page={content} />;
}

Other stacks

@xenia-martech/sdk-js/edge has no Next.js, React or DOM dependency. It runs in Node, edge functions and workers.

import {
  createXeniaEdge, deviceOf, edgeConsent, encodeVariant, isBot,
  localTime, readTrail, swapGroups, viewerGeo, withView,
} from "@xenia-martech/sdk-js/edge";
 
const edge = createXeniaEdge({ token: process.env.XENIA_SDK_TOKEN!, budgetMs: 150 });
 
// per page request
if (isBot(req.headers.get("user-agent"))) return next();
const keys = await edge.match(host, path);                        // [] → not targeted
const { geo } = viewerGeo(req, { trust: ["x-vercel-ip-country"] }); // only your host's headers
const outcome = await edge.decide(keys ?? [], {
  host, path, visitorId,
  facts: { ...localTime(geo, new Date()), device: deviceOf(req.headers), ...(geo ? { geo } : {}) },
  ...(edgeConsent(req.headers).analytics
    ? { trail: withView(readTrail(cookies.get("xenia_trail")), path) }
    : {}),
});
const groups = swapGroups(outcome.decisions);
if (groups.length) rewrite(`/xv/${await encodeVariant(groups, secret)}${path}`);

A PHP storefront can use Xenia's PHP SDK, which routes the same pages to the edge automatically.

Facts your rules can use

Your proxy sends the visitor's context with each decision:

  • Page and campaign: path, query, UTM fields, landing page and referrer.
  • Device and time: device type, and the visitor's local time and season.
  • Location: geo.country, geo.city and so on. It must come from your edge, because Xenia only sees your server. viewerGeo reads a location header only when you list it in trust, since a visitor can send any header. Name the ones your host sets, for example x-vercel-ip-country on Vercel or cf-ipcountry behind Cloudflare.
  • Browsing: the visitor's recent pages (the trail cookie) and stored profile, for Visitor Intent steps and profile.* rules.
  • Weather: createWeatherFacts({ unit }) adds temperature_now, avg_temperature_next_7_days and weather_condition, never holding a decision past its budget.

edgeConsent reads the consent cookie the browser SDK writes:

SignalEffect
No consent cookieDecide, and send and keep the trail and landing facts
personalization: falseDon't call Xenia. Serve base content.
analytics: falseStill decide, but keep no trail or click cookies
Sec-GPC: 1 or DNT: 1Treated as analytics: false

Browser signals

Turn on the browsing signals in the browser client so decisions see the page the visitor just left:

<XeniaProvider pageViews pageLeave trail navClicks contentClicks {...config}>

See Browsing signals.

Impressions and clicks

Stamp each personalized section so the browser SDK reports impressions and clicks. slotAttributes(slot) returns the attributes to spread on it. Exposures are recorded by Xenia when it decides, so don't report them again.

Debugging and QA

Turn these on only in development or on a QA deploy:

  • xeniaEdgeProxy({ debug: true }) records each decision, and <XeniaDebugPanel /> from /client/react shows it in a small card: the decision per content key, the journey path it took, the visitor's location and profile. Add your own rows with debugInfo(info).
  • xeniaEdgeProxy({ qa: true }) lets a tester place the visitor in a city (?xn_geo=london) or decide as of a date (?xn_date=2026-12-24) for the rest of the visit.

Several instances

Decisions are cached in each process's memory. On serverless or multi-region hosts, share them with tieredDecisionCache(store) over your own store, for example Redis. A store that is down or slower than 50 ms counts as a miss and never breaks a page.