What is your developer-dependent CMS actually costing you? Calculate your costs and get a full report
What is your developer-dependent CMS actually costing you? Calculate your costs and get a full report
Fully Featured Starter
How the Agility demo site swaps hero copy, logos and pricing by audience and region from URL parameters, while every page stays statically rendered.
The demo site changes its hero, its customer logos and its pricing tiers based on ?audience= and ?region= in the URL. The pages are still prerendered. You get a working pattern for personalization that does not make every request dynamic, and the steps to copy it into your own Agility site.
The code lives in the demo repo. The pieces are:
| Concern | File |
|---|---|
| Query param whitelist and path encoding | src/proxy.ts |
| Decoding the params | src/lib/cms/getAgilityPage.ts |
| Name to contentID lookup | src/lib/utils/audienceRegionUtils.ts |
| Hero personalization | src/components/agility-components/PersonalizedBackgroundHero.tsx |
| Logo filtering | src/components/agility-components/personalized-logo-strip/PersonalizedLogoStrip.tsx |
| Pricing by region | src/components/agility-components/pricing/PricingCards.tsx |
| Client hook | src/lib/hooks/useAudienceRegionParams.ts |
| Selector UI | src/components/preview-bar.tsx |
Personalization is plain content. There is no rules engine.
audiences) with a name, a description and an icon.regionID text field that holds the Region's content ID.The two components that use them:
The URL values map to content like this:
| Param | Value | Example |
|---|---|---|
audience | The audience name, lower-cased, with everything except letters, digits, dashes and underscores removed | "Financial Services" becomes financialservices. "E-commerce / Retail" becomes e-commerceretail. |
region | The exact region name | Canada, UK |
The audience rule is toAudienceParam in useAudienceRegionParams.ts:
export const toAudienceParam = (name: string) => name.toLowerCase().replace(/[^a-zA-Z0-9-_]/g, '')
The server applies the same expression when it matches (see getAudienceContentID below). Region matching is a plain r.name === regionName.
Under Cache Components (cacheComponents: true in next.config), a page can be prerendered into a static shell and served from the CDN. If the page reads searchParams, it becomes dynamic and renders on every request. That defeats the point of a static site.
The demo avoids it by moving the query string into the path. The proxy (src/proxy.ts) does four things:
audience, region and q survive. Tracking params such as utm_* or gclid are dropped, so a campaign link does not create a new page variant./pricing?region=UK becomes the internal path /pricing/~~~region%3DUK~~~.const ALLOWED_QUERY_PARAMS = ['audience', 'region', 'q'] // Whitelist of allowed query params
const MAX_QUERY_STRING_LENGTH = 500 // Maximum length for query string encoding
// ...
if (hasSearchParams) {
const searchParamPortion = `~~~${encodeURIComponent(searchParams)}~~~`
pathname = pathname.endsWith("/") ? `${pathname}${searchParamPortion}` : `${pathname}/${searchParamPortion}`
}
That snippet is from src/proxy.ts. A path like /pricing/~~~region%3DUK~~~ is just another catch-all route segment, so Next.js can match it with the same [locale]/[...slug] route as every other page.
getAgilityPage (src/lib/cms/getAgilityPage.ts) looks at the last slug segment. If it starts and ends with ~~~, it strips the markers, decodes the value, splits it into key/value pairs and removes the segment from the slug before it resolves the sitemap node:
let lastSlug = slugParts[slugParts.length - 1]
const searchParams: { [key: string]: string } = {}
if (lastSlug && lastSlug.startsWith("~~~") && lastSlug.endsWith("~~~")) {
lastSlug = lastSlug.replace(/~~~+/g, "")
const decoded = decodeURIComponent(lastSlug)
const parts = decoded.split("&").map(part => part.trim())
parts.forEach(part => {
const kvp = part.split("=")
if (kvp.length === 2) {
searchParams[kvp[0]] = kvp[1]
}
})
slugParts = slugParts.slice(0, slugParts.length - 1)
if (slugParts.length === 0) slugParts = [""]
}
The result is returned as globalData: { searchParams }. The page route in src/app/[locale]/[...slug]/page.tsx reads agilityData.globalData["searchParams"] and passes it to the page template. Components receive it as globalData.searchParams. The same file filters ~~~ segments out of the slug when it checks for the home page.
Two things to know about this decoder:
New+Zealand (the proxy builds the string with URLSearchParams, which writes spaces as +) and will not match a region of that name. The demo's four region names have no spaces. If yours do, decode + in this function.= is dropped.Because the variants are separate paths, each combination is cached on its own. That is also why the whitelist and length cap matter: an unbounded query string would let anyone create unlimited cache entries.
src/lib/utils/audienceRegionUtils.ts turns the URL value into a content ID. It reads the full Audience (or Region) list through getAudienceListingWithContentID or getRegionListingWithContentID, which fetch the audiences and regions lists with content IDs included, and finds the match:
const audience = audiences.find(a => a.name.toLowerCase().replace(/[^a-zA-Z0-9-_]/g, '') === audienceName)
return audience ? audience.contentID : null
const region = regions.find(r => r.name === regionName)
return region ? region.contentID : null
If there is no param or no match, the function returns null and the component renders its defaults.
The component fetches its own content item, then its list of Personalized Hero Items. It builds the default content first. If the visitor has an audience, it finds the hero item whose Audience dropdown has that content ID and overlays it field by field:
selectedContent = {
heading: personalizedContent.fields.heading || heading,
description: personalizedContent.fields.description || description,
cta1: personalizedContent.fields.cta1 || cta1,
cta2: personalizedContent.fields.cta2 || cta2,
backgroundType: personalizedContent.fields.backgroundType || backgroundType,
backgroundImage: personalizedContent.fields.backgroundImage || backgroundImage,
}
An editor can personalize only the heading and leave everything else blank. The blank fields fall back to the component's defaults. The component also renders a PersonalizationTracker to report which variant showed (see A Provider-Agnostic Analytics Layer with PostHog in Next.js for what is sent).
The strip fetches up to 250 Customer Profiles, then filters in code when an audience is set:
const audienceContentID = await getAudienceContentID(searchParams, languageCode)
if (audienceContentID) {
customers = {
...customers,
items: customers.items.filter(customer => customer.fields.audience?.contentID === audienceContentID)
}
}
With no audience, every customer shows. A comment in the file marks the in-code filter as a TODO to improve.
Pricing Cards reads the region param the same way (getRegionContentID). Without a region it shows tiers that have no regionID, the defaults. With a region it shows only tiers whose regionID equals that Region's content ID. The regionID is a text field, so the component parses it with parseInt.
useAudienceRegionParams(audiences, regions) in src/lib/hooks/useAudienceRegionParams.ts reads audience and region from useSearchParams() and gives you the matching items from the lists you pass in. It returns:
| Key | What it is |
|---|---|
selectedAudience, selectedRegion | The matching item, or null |
selectedAudienceName, selectedRegionName | The raw URL values, or null |
setAudience(audience | null), setRegion(region | null) | Update the URL with router.push |
clearAudience(), clearRegion(), clearAll() | Remove one or both params |
updateParams(audienceName, regionName) | Set both at once |
hasSelection | true if either is selected |
displayName | A label such as Financial Services • UK or All Audiences • All Regions |
audiences, regions | The lists you passed in |
Setting an audience writes the toAudienceParam form into the URL. The setters also send audience-changed and region-changed analytics events when the analytics client is ready.
The PreviewBar component (src/components/preview-bar.tsx) is the picker. The layout fetches the audience and region lists and passes them in as props. The bar renders as a floating button, and its panel has an Audience dropdown and a Region dropdown that call setAudience and setRegion from the hook. Selecting one navigates to the same path with the new query string. The proxy then maps it to the right prerendered variant.
The demo shows the bar on the live site "for illustration purposes", per a comment in the layout. Your site would likely not ship a visitor-facing picker.
src/components/AudienceRegionUtils.tsx holds three small helpers built on the hook: AudienceRegionIndicator (a "Current Context" box with a Clear button), ConditionalContent and useConditionalContent. They are examples and nothing else in the demo imports them. Note that they compare allowed names against the audience's display name, so pass names like "Financial Services", not the URL form.
Query params are a good way to test and demonstrate personalization. Anyone can edit the URL, and links with a param are shareable, so treat it as a preview of what a visitor would see, not as a secret. It does not detect who the visitor is.
The demo has @agility/geo as a dependency, but it is not used for location detection. The code imports it only for schema.org JSON-LD (buildJsonLd) and its types. Detecting a visitor's region at the edge, for example from your host's geolocation headers in the proxy, and then writing it into the same ~~~ segment, is a possible next step. The demo does not do it.
toAudienceParam does.~~~...~~~ with a rewrite.globalData.searchParams. Do not read searchParams in the page.null when nothing matches.useSearchParams and router.push is enough.For caching and revalidation behaviour, read Caching with Next.js and Agility.