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

Fetch entry variants and cache them per variant

•
6 min read

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:

// 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():

// 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():

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:

  1. Starts from the base entry.

  2. Applies the overrides of each matching entry variant.

  3. Leaves fields that no variant overrides untouched.

  4. 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 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:

// 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 and the chapter on 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.

Frequently asked questions

  • Does variants() work on queries as well as single entries?

    Yes. Call variants() on entry() before query() or find(), or on entry(uid) before fetch(). The SDK sends the aliases in the x-cs-variant-uid header.

  • What does the CDA return if an entry has no entry variant for an alias?

    The base entry. Aliases that do not apply to an entry are ignored for that entry.

  • Why not use stale-while-revalidate?

    The Personalize Launch setup recommends must-revalidate so a visitor never gets an outdated variant page while a refresh happens in the background.

  • Is it safe to cache personalized HTML on a shared CDN?

    Yes, as long as the page depends only on the variant parameter. Anything user-specific, like a name or a cart count, must load client-side.