# Audience and Region Personalization with Next.js

> Source: https://agilitycms.com/docs/nextjs/audience-and-region-personalization-with-next-js

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.

## See it in the demo

- Open [demo.agilitycms.com](https://demo.agilitycms.com) and note the hero heading.
- Open [demo.agilitycms.com/?audience=healthcare](https://demo.agilitycms.com/?audience=healthcare). The hero heading and background change, and the logo strip shows healthcare customers.
- Use the floating Agility button on the right edge of the page. Open it and pick an Audience or a Region. It rewrites the URL for you.

The code lives in the [demo repo](https://github.com/agility/nextjs-demo-site-2026). The pieces are:

| Concern | File |
| --- | --- |
| Query param whitelist and path encoding | [`src/proxy.ts`](https://github.com/agility/nextjs-demo-site-2026/blob/main/src/proxy.ts) |
| Decoding the params | [`src/lib/cms/getAgilityPage.ts`](https://github.com/agility/nextjs-demo-site-2026/blob/main/src/lib/cms/getAgilityPage.ts) |
| Name to contentID lookup | [`src/lib/utils/audienceRegionUtils.ts`](https://github.com/agility/nextjs-demo-site-2026/blob/main/src/lib/utils/audienceRegionUtils.ts) |
| Hero personalization | [`src/components/agility-components/PersonalizedBackgroundHero.tsx`](https://github.com/agility/nextjs-demo-site-2026/blob/main/src/components/agility-components/PersonalizedBackgroundHero.tsx) |
| Logo filtering | [`src/components/agility-components/personalized-logo-strip/PersonalizedLogoStrip.tsx`](https://github.com/agility/nextjs-demo-site-2026/blob/main/src/components/agility-components/personalized-logo-strip/PersonalizedLogoStrip.tsx) |
| Pricing by region | [`src/components/agility-components/pricing/PricingCards.tsx`](https://github.com/agility/nextjs-demo-site-2026/blob/main/src/components/agility-components/pricing/PricingCards.tsx) |
| Client hook | [`src/lib/hooks/useAudienceRegionParams.ts`](https://github.com/agility/nextjs-demo-site-2026/blob/main/src/lib/hooks/useAudienceRegionParams.ts) |
| Selector UI | [`src/components/preview-bar.tsx`](https://github.com/agility/nextjs-demo-site-2026/blob/main/src/components/preview-bar.tsx) |

## The CMS side

Personalization is plain content. There is no rules engine.

- **Audience**: a content list (reference name `audiences`) with a name, a description and an icon.
- **Region**: a content list with a name. The demo has Canada, USA, UK and Australia.
- **Customer Profile**: a customer with a name, a logo and an Audience content link.
- **Personalized Hero Item**: alternate hero content (heading, description, two CTAs, background) with an Audience dropdown. Each Personalized Background Hero component points at a list of these.
- **Pricing Tier**: includes a Region, stored as a `regionID` text field that holds the Region's content ID.

The two components that use them:

- **Personalized Background Hero** has default heading, description, CTAs and background, plus a list of Personalized Hero Items.
- **Personalized Logo Strip** has a list of Customer Profiles to show.

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`:

```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`.

## Why the proxy is involved

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`](https://github.com/agility/nextjs-demo-site-2026/blob/main/src/proxy.ts)) does four things:

1. **Whitelists params.** Only `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.
2. **Caps the length.** If the filtered query string is longer than 500 characters, it is ignored.
3. **Encodes the rest into the path.** `/pricing?region=UK` becomes the internal path `/pricing/~~~region%3DUK~~~`.
4. **Rewrites, not redirects.** The visitor's URL stays clean. The rewrite also adds the default locale segment when the path has none.

```ts
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.

### Decoding in the page route

`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:

```ts
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:

- It copies the value as-is. A value with a space, such as a region called "New Zealand", arrives as `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.
- A pair with more than one `=` 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.

## Server side: choosing the content

### Name to content ID

`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:

```ts
const audience = audiences.find(a => a.name.toLowerCase().replace(/[^a-zA-Z0-9-_]/g, '') === audienceName)
return audience ? audience.contentID : null
```

```ts
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.

### Personalized Background Hero

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**:

```ts
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](/docs/nextjs/analytics-layer-with-posthog-in-next-js) for what is sent).

### Personalized Logo Strip

The strip fetches up to 250 Customer Profiles, then filters in code when an audience is set:

```ts
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

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`.

## Client side

### The hook

`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 selector

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.

### Helper components

`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.

## Production note: this is a demo mechanism

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.

## Build the same pattern in your own site

1. **Model the content.** Create Audience and Region lists. Add an Audience content link to the things you want to filter (Customer Profile in the demo) and a Region reference to anything you want to vary by region (the demo stores the region content ID in a text field on Pricing Tier).
2. **Add alternates to your component.** Give the component its default fields and a list of alternate items, each with an Audience dropdown, like Personalized Hero Item. Keep every alternate field optional so it can fall back.
3. **Pick a URL contract.** Decide the param names and how a CMS name becomes a URL value. Use one function for both reading and writing, as `toAudienceParam` does.
4. **Whitelist in the proxy.** Keep only your params, cap their length, and move them into a trailing path segment such as `~~~...~~~` with a rewrite.
5. **Decode in the page route.** Strip the marker segment before you look up the page and expose the params as `globalData.searchParams`. Do not read `searchParams` in the page.
6. **Resolve the content ID on the server.** Fetch the Audience and Region lists with content IDs, match the param, and return `null` when nothing matches.
7. **Choose content in the component.** Filter lists or overlay fields, falling back to defaults.
8. **Add a picker.** A client component that reads and writes the URL with `useSearchParams` and `router.push` is enough.
9. **Plan for real detection.** When you are ready, set the same params from the edge instead of from a picker.

For caching and revalidation behaviour, read [Caching with Next.js and Agility](/docs/nextjs/caching-with-next-js-and-agility).

## Related

- [Using the Advanced Next.js Demo Site](/docs/nextjs/using-the-advanced-next-js-demo-site)
- [Caching with Next.js and Agility](/docs/nextjs/caching-with-next-js-and-agility)
- [Multi-Locale Support with Next.js](/docs/nextjs/multi-locale-support-with-next-js)
- [A/B/n Testing in Agility CMS](/docs/owners-admins/a-b-n-testing-in-agility-cms)
- [PostHog](/docs/apps/posthog)
- [A Provider-Agnostic Analytics Layer with PostHog in Next.js](/docs/nextjs/analytics-layer-with-posthog-in-next-js)

---

## Related pages

- [Using the Advanced Next.js Demo Site](https://agilitycms.com/docs/nextjs/using-the-advanced-next-js-demo-site.md)
- [Shared-Element Page Transitions with React ViewTransition](https://agilitycms.com/docs/nextjs/view-transitions-with-next-js.md)
- [A Provider-Agnostic Analytics Layer with PostHog in Next.js](https://agilitycms.com/docs/nextjs/analytics-layer-with-posthog-in-next-js.md)
- [AI Search, Clean Markdown and an MCP Server in a Next.js Site](https://agilitycms.com/docs/nextjs/ai-search-markdown-and-mcp-endpoints.md)

Index of every docs page: https://agilitycms.com/docs/llms.txt
