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 Next.js demo site wraps PostHog in a small analytics facade that tags every event with Agility page and content IDs, and how to add your own tracking.
The demo site never calls PostHog directly from a component. Every component calls one analytics object, which adds Agility CMS context to the event and hands it to a provider. This article walks through that layer so you can reuse it or adapt it.
It covers the facade, the event taxonomy, the trackers and how events carry page and content IDs. It does not cover PostHog setup, the raw provider pattern, HogQL queries or creating experiments. For those, read the PostHog app guide and A/B/n Testing in Agility CMS.
[Analytics.track], [Analytics.page] and so on.src/lib/analytics/index.tssrc/lib/analytics/posthog-provider.tssrc/components/analytics/src/instrumentation-client.tsFor the rest of the site, see Using the Advanced Next.js Demo Site.
component -> analytics.track(...) (src/lib/analytics/index.ts)
|
v
activeProvider (PostHogProvider, posthog-provider.ts)
|
PostHog ready? yes -> posthog.capture(...)
no -> queue, poll window.posthog, flush
^
|
instrumentation-client.ts loads posthog-js after the page is idle
and sets window.posthog
| File | Job |
|---|---|
src/lib/analytics/index.ts | The analytics facade, typed helper methods, getTrackingContext() |
src/lib/analytics/types.ts | Event property types and the AnalyticsProvider interface |
src/lib/analytics/events.ts | AnalyticsEvents constants, scroll and time milestones |
src/lib/analytics/posthog-provider.ts | The only file that knows about PostHog in the browser |
src/lib/analytics/agility-context.ts | Reads page and content IDs from the DOM |
src/lib/analytics/hooks/ | useScrollTracking and useTimeOnPage |
src/components/analytics/ | AnalyticsProvider, UserIdentifier, PageviewTracker, EngagementTracker, PersonalizationTracker |
src/lib/posthog/ | Server-side PostHog helpers (see below) |
The facade talks to whatever implements AnalyticsProvider, defined in types.ts:
export interface AnalyticsProvider {
name: string
init(): void
identify(userId: string, traits?: UserTraits): void
track(event: string, properties?: EventProperties): void
page(name: string, properties?: PageViewProperties): void
group(groupId: string, traits?: GroupTraits): void
reset(): void
isReady(): boolean
}
The facade in index.ts picks one provider with a single constant:
const activeProvider: AnalyticsProvider = PostHogProvider
That constant is the plug-in point. A second provider would be another object that implements this interface, and activeProvider would point at it. The demo ships only the PostHog provider, and the facade holds exactly one active provider. It does not fan out to several at once.
src/instrumentation-client.ts is Next.js's client instrumentation file, so it runs on every page load. The demo does not import posthog-js statically there. Its comment says a static import put about 76 kB gzipped of analytics ahead of the content the visitor came for.
Instead the file schedules a dynamic import:
const loadPostHog = async () => {
const postHogKey = process.env.NEXT_PUBLIC_POSTHOG_KEY
const postHogHost = process.env.NEXT_PUBLIC_POSTHOG_HOST
if (!postHogKey || !postHogHost) return
try {
const { default: posthog } = await import('posthog-js')
posthog.init(postHogKey, {
api_host: postHogHost,
defaults: '2025-05-24',
})
window.posthog = posthog
} catch (error) {
console.error('Could not initialize PostHog.', error)
}
}
const scheduleAnalytics = () => {
if ('requestIdleCallback' in window) {
window.requestIdleCallback(() => { void loadPostHog() }, { timeout: 4000 })
} else {
setTimeout(() => { void loadPostHog() }, 1500)
}
}
if (document.readyState === 'complete') {
scheduleAnalytics()
} else {
window.addEventListener('load', scheduleAnalytics, { once: true })
}
The order is: wait for the window load event, then wait for an idle moment (at most 4 seconds), then download and initialise PostHog. Browsers without requestIdleCallback (the file's comment names Safari) wait 1.5 seconds after load instead. The result is exposed as window.posthog, which is how the provider finds it.
Two details to know:
init call does not set capture_pageview. The PostHog app guide sets it to false in its example because the site sends its own $pageview. If you copy the demo's init, check your PostHog project for duplicate pageviews.instrumentation-client.ts also registers a window error listener that calls reportError(event.error). That is the browser's built-in reportError, not part of the analytics facade. The file's own comment says "send to your error tracking service", so treat it as a placeholder.Because PostHog loads late, the provider copes with it not being there yet. In posthog-provider.ts, getPostHog() returns the client only when window.posthog.__loaded is true. If it is not, identify, track, page and group push the call onto an in-memory eventQueue and start waitForPostHogAndFlush(), which retries every 100 ms and then replays the queue in order.
The trackers also check analytics.isReady() themselves and retry on a 100 ms timer before calling the facade. So in practice the trackers wait, and the provider's queue is a second safety net for any code that calls analytics.track() without checking.
PostHog's own pageview knows the URL, not the CMS record behind it. The Agility app's dashboards need Agility IDs, so the demo reads them from the DOM.
The page template renders them on <main> (in src/app/[locale]/[...slug]/page.tsx):
<main data-agility-page={agilityData.page?.pageID} data-agility-dynamic-content={agilityData.sitemapNode.contentID}>
Each component sets data-agility-component={contentID} on its outer element. The attribute appears on Hero, RichTextArea, PostDetails, the pricing components and others.
getAgilityContext() in agility-context.ts turns those into one object:
export interface AgilityContext {
pageID?: number // from [data-agility-page]
contentIDs?: number[] // data-agility-dynamic-content + every [data-agility-component]
locale?: string // first URL segment, if it looks like a locale
}
Note that locale comes from the first path segment, matched against ^[a-z]{2}(-[a-z]{2})?$. A path like /en-us/pricing gives en-us. A site that does not put the locale in the URL gets no locale from this function.
getNearestContentID(element) does element.closest('[data-agility-component]'). The outbound link tracker uses it to attribute a click to the component that contains the link.
getTrackingContext() in index.ts combines all of this with the URL's audience, region and utm_* query parameters. The scroll, time and outbound trackers spread that result into their events, which is why every one of them carries pageID and contentIDs.
AnalyticsProvider (the component, not the provider object) is mounted once in src/app/[locale]/layout.tsx, inside a Suspense boundary because its children read search params:
<Suspense fallback={null}>
<AnalyticsProvider locale={locale} />
</Suspense>
It renders three components, each of which can be switched off with a disable... prop:
| Component | What it does |
|---|---|
UserIdentifier | Calls analytics.identify() with locale, audience, region, firstSeen and sessionCount. Calls again when audience, region or locale changes. |
PageviewTracker | Calls analytics.page() on every path or search-param change, after a 100 ms delay so the title is set. |
EngagementTracker | Runs useScrollTracking, useTimeOnPage and the outbound link listener. |
A fourth component, PersonalizationTracker, is not mounted by the provider. A server component drops it in next to personalized content. The demo's PersonalizedBackgroundHero does this.
UserIdentifier uses an ID it generates itself (anon_<timestamp>_<random>, stored in localStorage under analytics_user_id) via getOrCreateUserId(). It keeps a session count in localStorage, and a new session starts after 30 minutes of inactivity.
events.ts defines the milestones:
export const ScrollMilestones = [25, 50, 75, 100] as const
export const TimeMilestones = [30, 60, 120, 300] as const // seconds
useScrollTracking debounces the scroll handler (100 ms), computes depth from scrollY against the scrollable height, and fires each milestone once per page. A page that is too short to scroll counts as 100. It also checks the starting position, so a visitor who lands mid-page fires the lower milestones straight away.
useTimeOnPage ticks once a second and only counts time while document.visibilityState is visible. Both hooks reset when the path or search params change.
EngagementTracker adds one click listener on document. It finds the nearest <a>, and if the href is not #... or /... and the hostname differs from the current one, it fires outbound_link_clicked with the URL, the first 100 characters of the link text, the path, pageID and the nearest contentID.
The code names events with constants in AnalyticsEvents (events.ts). The constant name is what you write in code. The string is what PostHog stores. They are not always the obvious match.
One difference matters most: analytics.page() does not use PAGE_VIEWED. The provider sends PostHog's built-in $pageview. The PAGE_VIEWED constant ('page_viewed') is defined but nothing in the demo fires it.
| PostHog event | Constant | When it fires | Key properties |
|---|---|---|---|
$pageview | (none, sent by PostHogProvider.page()) | Path or search params change | $current_url, $pathname, $title, $referrer, page_name, locale, audience, region, utm_*, load_time_ms (first full load only), pageID, contentIDs |
scroll_milestone | SCROLL_MILESTONE | Depth 25, 50, 75, 100 reached | depth, timeToReach (ms), path, locale, audience, region, pageID, contentIDs |
time_milestone | TIME_MILESTONE | 30, 60, 120, 300 visible seconds | seconds, isVisible, path, locale, pageID, contentIDs |
outbound_link_clicked | OUTBOUND_LINK_CLICKED | Click on a link to another host | url, text, path, locale, pageID, contentID |
personalized_content_viewed | PERSONALIZED_CONTENT_VIEWED | PersonalizationTracker mounts with isPersonalized true | personalizationType, audience, region, component, contentID, path |
personalization_applied | PERSONALIZATION_APPLIED | PersonalizationTracker mounts with an audience or region but isPersonalized false | same as above |
audience_changed | AUDIENCE_CHANGED | Visitor picks or clears an audience (useAudienceRegionParams) | personalizationType, audience, previousAudience, path |
region_changed | REGION_CHANGED | Visitor picks or clears a region | personalizationType, region, previousRegion, path |
experiment_exposure | EXPERIMENT_EXPOSURE | ABTestHeroClient has a flag value and knows which variant it shows | experimentKey, variant, component, contentID, path |
experiment_interaction | EXPERIMENT_INTERACTION | CTA click in the A/B hero | experimentKey, variant, component, contentID, action (cta_click), ctaText, ctaHref |
cta_clicked | CTA_CLICKED | CTA click in the A/B hero (via trackCTAClick) | ctaName, ctaUrl, ctaText, component, location, path |
Every event sent through PostHogProvider.track() also gets a timestamp property (ISO string) if you did not set one.
events.ts also declares constants for video, form, conversion, AI search, AI agent and error events (video_played, form_started, form_submitted, conversion, demo_requested, ai_search_started, error_occurred and others), and the facade has helpers such as trackFormSubmitted, trackConversion, trackDemoRequested and trackError. In the demo's src/, nothing outside the analytics module calls them. They are a starting vocabulary, not tracked behaviour. Rename or delete them to suit your site.
Personalization events come from two places. PersonalizationTracker fires on mount, once per mount. It skips tracking when neither an audience nor a region is active. useAudienceRegionParams fires audience_changed and region_changed when the visitor changes the selection, and again when they clear it. On a clear, the event carries only previousAudience or previousRegion.
For A/B tests, ABTestHeroClient uses PostHog's useFeatureFlagVariantKey hook to pick the variant. The component's comments say the hook also sends PostHog's own $feature_flag_called event. The demo adds experiment_exposure through the facade, so the exposure carries the same contentID as everything else. It fires once the flag has a value, retrying for up to 5 seconds if analytics is not ready. See A/B/n Testing in Agility CMS for how to set the experiment up.
The browser side degrades quietly:
instrumentation-client.ts returns early if NEXT_PUBLIC_POSTHOG_KEY or NEXT_PUBLIC_POSTHOG_HOST is not set, so window.posthog is never defined.analytics.isReady() stays false. Nothing throws and the page renders as normal.PageviewTracker, UserIdentifier and PersonalizationTracker retry every 100 ms with no upper limit. The A/B hero gives up after 50 tries. A site that deliberately runs without PostHog should not mount AnalyticsProvider, or should add a retry cap.The server helpers in src/lib/posthog/ also tolerate missing keys: getPostHogClient() returns null, trackEvent() returns without doing anything, and getFeatureFlagVariant() returns undefined.
There is one thing that does not tolerate them. src/lib/env.ts lists both PostHog variables as required and throws Missing required environment variable: ... when one is empty. In the current code nothing imports that file, so it does not affect the running site. If you wire env in, you are making PostHog mandatory.
When NODE_ENV is development, the facade logs every call through debugLog, for example [Analytics.track] cta_clicked {...}. The PostHog provider also writes a few unconditional console.log lines (user identified, queue flushed, identity reset), which appear in production builds too.
src/lib/posthog/ has four small modules built on posthog-node:
| File | Purpose |
|---|---|
get-client.ts | getPostHogClient(): a lazy singleton, null without keys |
track-event.ts | trackEvent(event, distinctId, properties?): wraps client.capture and swallows errors |
get-feature-flag-variant.ts | getFeatureFlagVariant(flagKey, distinctId, userProperties?): server-side flag evaluation, undefined on failure |
get-user-id.ts, get-cookie-name.ts | Distinct ID helpers |
Read these as scaffolding. getUserId() has the PostHog cookie lookup commented out with a TODO and always returns a fresh nanoid(). That means a server-side event or flag evaluation is not tied to the browser visitor. Nothing in the demo's src/ calls trackEvent, getFeatureFlagVariant or getUserId, because the A/B hero evaluates its flag in the browser (the comments explain that reading cookies on the server would make the route dynamic). If you use them, pass a distinct ID you trust.
Google Analytics is separate from the facade. layout.tsx renders <GoogleAnalytics gaId={gaId} /> from @next/third-parties/google when the gaId is set. The ID comes from the site settings content in the CMS (settings.googleAnalyticsID), not from an environment variable. Events sent through analytics go to PostHog only.
Import the facade and call a typed helper or track. Check the event constant exists first, or add one to events.ts.
"use client"
import { analytics } from "@/lib/analytics"
export function DownloadButton({ contentID, href }: { contentID: number; href: string }) {
return (
<a
href={href}
onClick={() => {
analytics.track("content_downloaded", {
contentID,
path: window.location.pathname,
})
}}
>
Download
</a>
)
}
CONTENT_DOWNLOADED already exists in AnalyticsEvents, so you can use AnalyticsEvents.CONTENT_DOWNLOADED instead of the string. If you want pageID and contentIDs on the event, spread getTrackingContext() into the properties.
If you call track before PostHog has loaded, the provider queues the event. You do not need the analytics.isReady() check the demo's trackers use, unless you want to avoid queuing.
Do not call analytics from a server component. PostHog is a browser library and is not available on the server, so the event would only sit in a queue and never be sent. Do two things instead:
Render the CMS ID on the element, so the engagement trackers can attribute scrolls and outbound clicks to it:
<section data-agility-component={contentID}>...</section>
For an event that must fire when the component appears, render a small client component that fires on mount. PersonalizationTracker is the demo's example, used in PersonalizedBackgroundHero:
<PersonalizationTracker
audience={audienceName}
component="PersonalizedBackgroundHero"
contentID={contentID}
isPersonalized={isPersonalized}
/>
Build yours the same way: "use client", a useEffect that calls analytics.track(), and return null. Pass plain values as props, not functions.
For events that come from the server itself, such as a route handler, use trackEvent() from src/lib/posthog/track-event.ts with a distinct ID you control.
AnalyticsEvents in events.ts (snake_case, action-oriented, as the file's header asks).types.ts that extends BaseEventProperties, if the event has its own fields.analytics object in index.ts.The event shows up in PostHog under the string value, and you can query it with the page and content IDs like any other. For HogQL examples and the properties the CMS app expects, see the PostHog app guide.