# A Provider-Agnostic Analytics Layer with PostHog in Next.js

> Source: https://agilitycms.com/docs/nextjs/analytics-layer-with-posthog-in-next-js

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](/docs/apps/posthog) and [A/B/n Testing in Agility CMS](/docs/owners-admins/a-b-n-testing-in-agility-cms).

## See it in the demo

- Live site: [demo.agilitycms.com](https://demo.agilitycms.com). In the browser console on a development build, every call is logged as `[Analytics.track]`, `[Analytics.page]` and so on.
- Facade: [`src/lib/analytics/index.ts`](https://github.com/agility/nextjs-demo-site-2026/blob/main/src/lib/analytics/index.ts)
- Provider: [`src/lib/analytics/posthog-provider.ts`](https://github.com/agility/nextjs-demo-site-2026/blob/main/src/lib/analytics/posthog-provider.ts)
- Trackers: [`src/components/analytics/`](https://github.com/agility/nextjs-demo-site-2026/tree/main/src/components/analytics)
- Lazy loader: [`src/instrumentation-client.ts`](https://github.com/agility/nextjs-demo-site-2026/blob/main/src/instrumentation-client.ts)

For the rest of the site, see [Using the Advanced Next.js Demo Site](/docs/nextjs/using-the-advanced-next-js-demo-site).

## How the pieces fit

```text
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 provider interface

The facade talks to whatever implements `AnalyticsProvider`, defined in `types.ts`:

```typescript
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:

```typescript
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.

## Lazy loading PostHog

`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:

```typescript
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:

- The `init` call does not set `capture_pageview`. The [PostHog app guide](/docs/apps/posthog) 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.

### How events wait for PostHog

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.

## Agility context on every event

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`):

```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:

```typescript
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`.

## The trackers

`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:

```tsx
<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.

### Scroll and time milestones

`events.ts` defines the milestones:

```typescript
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.

### Outbound links

`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`.

## Event reference

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.

### Defined but not fired

`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 and experiments

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](/docs/owners-admins/a-b-n-testing-in-agility-cms) for how to set the experiment up.

## When PostHog keys are missing

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.
- The cost is a little background polling. `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.

### Development logging

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.

## Server-side helpers

`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.

## GA4

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.

## Adding tracking to your own components

### In a client component

Import the facade and call a typed helper or `track`. Check the event constant exists first, or add one to `events.ts`.

```tsx
"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.

### In a server component

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:

1. Render the CMS ID on the element, so the engagement trackers can attribute scrolls and outbound clicks to it:

   ```tsx
   <section data-agility-component={contentID}>...</section>
   ```

2. 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`:

   ```tsx
   <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.

### Adding an event

1. Add a constant to `AnalyticsEvents` in `events.ts` (snake_case, action-oriented, as the file's header asks).
2. Add a properties interface in `types.ts` that extends `BaseEventProperties`, if the event has its own fields.
3. Optionally add a typed helper on the `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](/docs/apps/posthog).

## Related

- [PostHog app for Agility CMS](/docs/apps/posthog)
- [A/B/n Testing in Agility CMS](/docs/owners-admins/a-b-n-testing-in-agility-cms)
- [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]
- [Audience and Region Personalization with Next.js](/docs/nextjs/audience-and-region-personalization-with-next-js)(/docs/nextjs/multi-locale-support-with-next-js)

---

## Related pages

- [Using the Advanced Next.js Demo Site](https://agilitycms.com/docs/nextjs/using-the-advanced-next-js-demo-site.md)
- [Audience and Region Personalization with Next.js](https://agilitycms.com/docs/nextjs/audience-and-region-personalization-with-next-js.md)
- [Shared-Element Page Transitions with React ViewTransition](https://agilitycms.com/docs/nextjs/view-transitions-with-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
