Adds an Analytics view to the Payload admin that reads reports from the GA4 Data API using a Google service account, plus a client provider that loads gtag.js and fires page views and lead-action events. It registers REST endpoints under the analytics path and needs an access policy built on the companion guard plugin. Requires Payload 3.90 or later and a GA4 property with registered custom dimensions.
Installation
npm i @focus-reactive/payload-plugin-analytics37
Stars
5
Forks
33
Open Issues
Today
Last Updated
821
Weekly Downloads
v2.0.1
npm Version
1.5 MB
Unpacked Size
6
Dependencies
37+22 since Sep 7
| Date | Stars |
|---|---|
| Dec 6, 2026 | 37 |
| Dec 5, 2026 | 37 |
| Dec 4, 2026 | 37 |
| Dec 3, 2026 | 37 |
| Dec 2, 2026 | 37 |
| Dec 1, 2026 | 36 |
| Nov 30, 2026 | 35 |
| Nov 29, 2026 | 35 |
| Nov 28, 2026 | 34 |
| Nov 27, 2026 | 34 |
| Nov 26, 2026 | 34 |
| Nov 25, 2026 | 34 |
| Nov 24, 2026 | 34 |
| Nov 23, 2026 | 34 |
| Nov 22, 2026 | 34 |
| Nov 21, 2026 | 34 |
| Nov 20, 2026 | 33 |
| Nov 19, 2026 | 32 |
| Nov 18, 2026 | 32 |
| Nov 17, 2026 | 32 |
| Nov 16, 2026 | 32 |
| Nov 15, 2026 | 32 |
| Nov 14, 2026 | 32 |
| Nov 13, 2026 | 32 |
| Nov 12, 2026 | 32 |
| Nov 11, 2026 | 32 |
| Nov 10, 2026 | 32 |
| Nov 9, 2026 | 31 |
| Nov 8, 2026 | 31 |
| Nov 7, 2026 | 31 |
| Nov 6, 2026 | 31 |
| Nov 5, 2026 | 31 |
| Nov 4, 2026 | 30 |
| Nov 3, 2026 | 30 |
| Nov 2, 2026 | 30 |
| Nov 1, 2026 | 30 |
| Oct 31, 2026 | 30 |
| Oct 30, 2026 | 30 |
| Oct 29, 2026 | 30 |
| Oct 28, 2026 | 30 |
| Oct 27, 2026 | 30 |
| Oct 26, 2026 | 30 |
| Oct 25, 2026 | 30 |
| Oct 24, 2026 | 29 |
| Oct 23, 2026 | 29 |
| Oct 22, 2026 | 29 |
| Oct 21, 2026 | 29 |
| Oct 20, 2026 | 29 |
| Oct 19, 2026 | 29 |
| Oct 18, 2026 | 29 |
| Oct 17, 2026 | 27 |
| Oct 16, 2026 | 26 |
| Oct 15, 2026 | 26 |
| Oct 14, 2026 | 26 |
| Oct 13, 2026 | 25 |
| Oct 12, 2026 | 25 |
| Oct 11, 2026 | 25 |
| Oct 10, 2026 | 25 |
| Oct 9, 2026 | 25 |
| Oct 8, 2026 | 25 |
| Oct 7, 2026 | 25 |
| Oct 6, 2026 | 24 |
| Oct 5, 2026 | 24 |
| Oct 4, 2026 | 24 |
| Oct 3, 2026 | 23 |
| Oct 2, 2026 | 22 |
| Oct 1, 2026 | 22 |
| Sep 30, 2026 | 20 |
| Sep 29, 2026 | 20 |
| Sep 28, 2026 | 20 |
| Sep 27, 2026 | 20 |
| Sep 26, 2026 | 19 |
| Sep 25, 2026 | 18 |
| Sep 24, 2026 | 18 |
| Sep 23, 2026 | 18 |
| Sep 22, 2026 | 18 |
| Sep 21, 2026 | 18 |
| Sep 20, 2026 | 18 |
| Sep 19, 2026 | 18 |
| Sep 18, 2026 | 18 |
| Sep 17, 2026 | 18 |
| Sep 16, 2026 | 18 |
| Sep 15, 2026 | 18 |
| Sep 14, 2026 | 18 |
| Sep 13, 2026 | 17 |
| Sep 12, 2026 | 17 |
| Sep 11, 2026 | 17 |
| Sep 10, 2026 | 16 |
| Sep 9, 2026 | 16 |
| Sep 8, 2026 | 16 |
| Sep 7, 2026 | 15 |
Shared by 15 plugins in focusreactive/payload-plugins.
635+543 since Sep 7
| Date | Weekly downloads |
|---|---|
| Dec 6, 2026 | 635 |
| Dec 5, 2026 | 708 |
| Dec 4, 2026 | 736 |
| Dec 3, 2026 | 800 |
| Dec 2, 2026 | 756 |
| Dec 1, 2026 | 714 |
| Nov 30, 2026 | 702 |
| Nov 29, 2026 | 552 |
| Nov 28, 2026 | 472 |
| Nov 27, 2026 | 486 |
| Nov 26, 2026 | 465 |
| Nov 25, 2026 | 468 |
| Nov 24, 2026 | 512 |
| Nov 23, 2026 | 576 |
| Nov 22, 2026 | 626 |
| Nov 21, 2026 | 737 |
| Nov 20, 2026 | 705 |
| Nov 19, 2026 | 676 |
| Nov 18, 2026 | 757 |
| Nov 17, 2026 | 727 |
| Nov 16, 2026 | 658 |
| Nov 15, 2026 | 723 |
| Nov 14, 2026 | 759 |
| Nov 13, 2026 | 758 |
| Nov 12, 2026 | 772 |
| Nov 11, 2026 | 825 |
| Nov 10, 2026 | 858 |
| Nov 9, 2026 | 965 |
| Nov 8, 2026 | 909 |
| Nov 7, 2026 | 827 |
| Nov 6, 2026 | 795 |
| Nov 5, 2026 | 773 |
| Nov 4, 2026 | 602 |
| Nov 3, 2026 | 606 |
| Nov 2, 2026 | 688 |
| Nov 1, 2026 | 664 |
| Oct 31, 2026 | 617 |
| Oct 30, 2026 | 613 |
| Oct 29, 2026 | 516 |
| Oct 28, 2026 | 467 |
| Oct 27, 2026 | 432 |
| Oct 26, 2026 | 254 |
| Oct 25, 2026 | 203 |
| Oct 24, 2026 | 165 |
| Oct 23, 2026 | 104 |
| Oct 22, 2026 | 149 |
| Oct 21, 2026 | 226 |
| Oct 20, 2026 | 219 |
| Oct 19, 2026 | 239 |
| Oct 18, 2026 | 342 |
| Oct 17, 2026 | 460 |
| Oct 16, 2026 | 613 |
| Oct 15, 2026 | 734 |
| Oct 14, 2026 | 763 |
| Oct 13, 2026 | 768 |
| Oct 12, 2026 | 734 |
| Oct 11, 2026 | 708 |
| Oct 10, 2026 | 589 |
| Oct 9, 2026 | 452 |
| Oct 8, 2026 | 313 |
| Oct 7, 2026 | 277 |
| Oct 6, 2026 | 290 |
| Oct 5, 2026 | 615 |
| Oct 4, 2026 | 598 |
| Oct 3, 2026 | 800 |
| Oct 2, 2026 | 852 |
| Oct 1, 2026 | 974 |
| Sep 30, 2026 | 990 |
| Sep 29, 2026 | 1,002 |
| Sep 28, 2026 | 683 |
| Sep 27, 2026 | 705 |
| Sep 26, 2026 | 614 |
| Sep 25, 2026 | 655 |
| Sep 24, 2026 | 562 |
| Sep 23, 2026 | 512 |
| Sep 22, 2026 | 526 |
| Sep 21, 2026 | 565 |
| Sep 20, 2026 | 485 |
| Sep 19, 2026 | 468 |
| Sep 18, 2026 | 382 |
| Sep 17, 2026 | 421 |
| Sep 16, 2026 | 491 |
| Sep 15, 2026 | 521 |
| Sep 14, 2026 | 540 |
| Sep 13, 2026 | 520 |
| Sep 12, 2026 | 418 |
| Sep 11, 2026 | 405 |
| Sep 10, 2026 | 321 |
| Sep 9, 2026 | 241 |
| Sep 8, 2026 | 164 |
| Sep 7, 2026 | 92 |
Each point is npm's rolling 7-day download count.
Health Score
Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.
Badge for your README
[](https://payloaddirectory.dev/plugins/1177993877-payload-plugin-analytics)<a href="https://payloaddirectory.dev/plugins/1177993877-payload-plugin-analytics"><img src="https://payloaddirectory.dev/badge/1177993877-payload-plugin-analytics.svg" alt="Payload Directory"></a>README
A GA4-backed analytics plugin for Payload CMS v3 + Next.js. Adds a full analytics dashboard inside the Payload admin — KPIs, traffic, top pages/sources/events, devices, geography, sessions, journeys, and lead-action conversions — plus a tiny client-side tracking layer for your front end. Optional A/B analytics tab integrates with @focus-reactive/payload-plugin-ab.
There are two halves:
analyticsPlugin() registers an admin dashboard view and REST endpoints that read your data from the GA4 Data API using a service account.<AnalyticsProvider> + ga4Provider() load gtag.js, track page views and route changes, and fire engagement / lead-action events to GA4.Copy and paste this prompt into your AI assistant (Cursor, Claude, etc.) to integrate the plugin into an existing Payload + Next.js project.
I want to add an analytics dashboard to my Payload CMS v3 + Next.js project using
@focus-reactive/payload-plugin-analytics. Follow these steps in order, and stop to ask me where a step says so.
## Rules you must follow
- Never write an access rule that admits every logged-in user: no `Boolean(req.user)`, no `() => true`,
no `({ req }) => !!req.user`. A rule names a role, or it is `nobody`.
- Do not invent roles. Ask me which roles may see each part of the dashboard.
- Write every policy entry by hand in `src/access.policy.ts`, and grant each capability and each
collection right explicitly to the roles I name. Nothing is open by default.
- When the boot or a request fails, fix the cause or ask me. Never use `anyone`, a looser gate,
`overrideAccess` or a removed or disabled check to make an error go away.
- Do not add `overrideAccess: true` anywhere, also not in `resolvePagePath` or in a custom block's `fetch`.
## How it works
The plugin has a server half and a client half:
- Server: analyticsPlugin() in payload.config.ts adds an admin view at /admin/analytics and endpoints
under /api/analytics/*. The endpoints read reports from the GA4 Data API with a Google service
account. Nothing is stored in the database; GA4 is the source of truth.
- Client: <AnalyticsProvider provider={ga4Provider({ measurementId })}> wraps the front end.
It loads gtag.js, tracks page_view on first load and on every route change, and fires engagement
and "lead_action" conversion events. It sends only campaign parameters (utm_*, gclid, ...) of a
page's query string to GA4.
It declares three capabilities that the project grants in its access policy:
- `viewAnalytics`: the dashboard, its overview and lead-action reports, journeys and custom blocks.
- `viewSessions`: the Sessions tab, with each visitor's session and its events.
- `viewAbResults`: the A/B tab. The user also needs read rights on an experiment in `ab-experiments`.
Page reports cover only the pages the user may read, and page titles come from those pages only.
## Prerequisites (GA4)
1. A GA4 property: note its Measurement ID (G-XXXXXXX) and numeric Property ID.
2. A Google Cloud service account with the Google Analytics Data API enabled. Create a JSON key
and grant the service account "Viewer" on the GA4 property (Admin → Property Access Management).
3. In GA4 → Admin → Custom definitions, register the EVENT-SCOPED custom dimensions and the
custom metric the plugin reads (see "Register custom dimensions and the conversion event"
in the README for the full table). At minimum:
- Custom dimensions (scope = Event): `fr_session_id`, `fr_session_start`, `fr_event_seq`,
`fr_lead_type`, and, if you use the A/B tab, `fr_ab_experiment`, `fr_ab_variant`,
`fr_ab_visitor_id`.
- Custom metric (scope = Event): `fr_elapsed_ms`.
## Step 1: install
pnpm add @focus-reactive/payload-plugin-analytics @focus-reactive/payload-plugin-guard
Check that `payload` is 3.90 or later; if it is not, upgrade it first.
## Step 2: ask me about roles
Look at the auth collection named in `admin.user` and the roles it has.
Ask me: "Which roles may open the analytics dashboard?", "Which roles may see individual visitor
sessions?" and "Which roles may see A/B test results?"
Wait for my answers. Write each answer as a gate in the policy file in step 3.
## Step 3: the access policy file
Open `src/access.policy.ts`, or create it if the project has none, following the guard README
(`defineAccessPolicy`, `gate`, `filter`, `nobody`, `anyone`, checked with `satisfies AccessPolicy<Config>`).
If you create it, every collection and global of the config needs an entry: move each existing
`access` of the project into the file, and ask me for every rule you cannot read from the code.
Add this entry for this plugin:
plugins: {
analytics: {
viewAnalytics: <the gate from my first answer>,
viewSessions: <the gate from my second answer>,
viewAbResults: <the gate from my third answer>,
},
},
## Step 4: register the plugin and wrap the config
// payload.config.ts
import { buildConfig } from 'payload'
import { withAccessPolicy } from '@focus-reactive/payload-plugin-guard'
import { analyticsPlugin } from '@focus-reactive/payload-plugin-analytics'
import { accessPolicy } from './access.policy'
export default withAccessPolicy(
accessPolicy,
buildConfig({
// ...the existing config
plugins: [
analyticsPlugin({
access: accessPolicy.plugins.analytics,
ga4: {
measurementId: process.env.GA4_MEASUREMENT_ID!, // G-XXXXXXX
propertyId: process.env.GA4_PROPERTY_ID!, // numeric
serviceAccount: {
clientEmail: process.env.GA4_CLIENT_EMAIL!,
// Env vars escape newlines: un-escape them.
privateKey: (process.env.GA4_PRIVATE_KEY ?? '').replace(/\\n/g, '\n'),
},
},
leadActions: {
types: ['phone_click', 'email_click', 'form_submit'], // lead types you fire
},
}),
],
})
)
The admin dashboard, header link and endpoints are added automatically.
## Step 5: wrap the front end with the provider (Client Component)
// app/providers.tsx
'use client'
import { AnalyticsProvider, ga4Provider } from '@focus-reactive/payload-plugin-analytics/client'
export function Analytics({ measurementId, children }) {
return <AnalyticsProvider provider={ga4Provider({ measurementId })}>{children}</AnalyticsProvider>
}
// app/layout.tsx (Server Component)
import { Analytics } from './providers'
export default function RootLayout({ children }) {
return (
<html><body>
<Analytics measurementId={process.env.NEXT_PUBLIC_GA4_MEASUREMENT_ID!}>{children}</Analytics>
</body></html>
)
}
Fire conversion events where they happen:
import { TrackLeadAction } from '@focus-reactive/payload-plugin-analytics/client'
<TrackLeadAction on="click" type="phone_click">
<a href="tel:+1234567890">Call us</a>
</TrackLeadAction>
## Step 6: verify, and show me the output
With the app running, send each request and show me the status code.
Every one of them must be refused. If one succeeds, the policy is wrong: stop and tell me.
1. Anonymous report, expect 401:
curl -i -X POST http://localhost:3000/api/analytics/kpis -H 'Content-Type: application/json' -d '{"dateRange":{"preset":"last-7d"}}'
2. The same request with the session cookie of a user whose role may not open the dashboard, expect 403.
3. POST /api/analytics/sessions with the same body and the session cookie of a user without
viewSessions, expect 403.
4. POST /api/analytics/ab/kpis with the same body and the session cookie of a user without
viewAbResults, expect 403.
5. Open /admin/analytics as a user without viewAnalytics: expect a 404 page and no chart icon in the header.
Then open /admin/analytics as a user with viewAnalytics and check that the reports load.
## Important notes
- ga4.measurementId must look like G-XXXXXXX and ga4.propertyId is required; otherwise the plugin
logs a warning and stays off.
- The service account private key must be a real multi-line PEM at runtime. When stored in an env
var, un-escape "\n" as shown above.
- The dashboard reads GA4 directly. New events take a few minutes to appear.
- The Lead Actions tab only works if "fr_lead_type" is registered as a custom dimension in GA4.
- AnalyticsProvider must be a client component boundary (it renders gtag scripts). Mount it once,
as high as possible: nesting it fires duplicate page_view events (a dev warning is logged).
GA4 is the single source of truth. The plugin never writes analytics data to your database — it reads GA4 on the server for the dashboard and writes to GA4 from the browser via gtag.js.
┌─────────────────────────── Browser ───────────────────────────┐
│ <AnalyticsProvider provider={ga4Provider(...)}> │
Your front end → │ • injects gtag.js │
│ • page_view on load + every route change │
│ • <Track> / <TrackLeadAction> / useAnalytics() → events │
└───────────────────────────────┬─────────────────────────────────┘
│ events
▼
┌──────────────────┐
│ GA4 property │
└────────┬─────────┘
│ Data API (service account)
▼
┌──────────────────────── Payload admin ─────────────────────────┐
│ analyticsPlugin() → /api/analytics/* endpoints │
│ → Analytics view at /admin/analytics │
│ KPIs · Top pages/sources/events · Devices · Geo · Sessions · │
│ Journeys · Lead actions · (optional) A/B tab │
└─────────────────────────────────────────────────────────────────┘
The dashboard view, the Analytics header icon, the admin providers, and all REST endpoints are injected into your Payload config automatically. You only register the plugin and mount the client provider.
The plugin talks to two GA4 surfaces: the browser sends events via gtag.js (Measurement ID), and the server reads reports via the GA4 Data API (Property ID + service account). Set both up once.
G-XXXXXXX. GA4 → Admin → Data Streams → your web stream.123456789). GA4 → Admin → Property Settings.client_email and private_key.GA4 → Admin → Property Access Management → add the service account's client_email with at least the Viewer role. Without this, every report returns a permission error.
GA4 → Admin → Custom definitions → Create custom dimension (scope = Event):
| Parameter name | Scope | Required for |
|---|---|---|
fr_session_id | Event | Sessions tab and Session drawer (session identity) |
fr_session_start | Event | Session start time / session ordering |
fr_event_seq | Event | Within-minute event ordering in journeys and drawer |
fr_lead_type | Event | Lead Actions tab |
fr_ab_experiment | Event | A/B tab (optional) |
fr_ab_variant | Event | A/B tab (optional) |
fr_ab_visitor_id | Event | A/B tab (optional) |
Then create the matching custom metric under the same Custom definitions screen → Create custom metric (scope = Event):
| Parameter name | Scope | Unit / Type | Required for |
|---|---|---|---|
fr_elapsed_ms | Event | Standard (ms) | Avg time-to-action on the Lead Actions tab |
The plugin fires lead conversions as a lead_action event carrying the fr_lead_type parameter (and fr_elapsed_ms for timing). GA4 only lets you query a custom parameter once it's registered as a dimension or metric, so these steps are mandatory for the tabs noted above. Dimensions that aren't registered degrade gracefully — the affected tab shows a "setup required" hint instead of failing.
# .env
GA4_MEASUREMENT_ID=G-XXXXXXX
GA4_PROPERTY_ID=123456789
[email protected]
GA4_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMIIE...\n-----END PRIVATE KEY-----\n"
NEXT_PUBLIC_GA4_MEASUREMENT_ID=G-XXXXXXX
Gotcha: env files store the private key with literal
\nsequences. Un-escape them before passing to the plugin:privateKey: process.env.GA4_PRIVATE_KEY!.replace(/\\n/g, '\n').
The plugin ships its React UI and charts as peer dependencies so it shares a single copy with your app. Install the plugin together with its required peers:
pnpm add @focus-reactive/payload-plugin-analytics @focus-reactive/payload-plugin-guard \
@payloadcms/ui @payloadcms/next @tanstack/react-query \
lucide-react react-day-picker recharts
| Peer dependency | Range | Why |
|---|---|---|
payload | ^3.90.0 | Core - the plugin targets Payload v3 |
@payloadcms/ui | ^3.90.0 | Admin UI primitives used by the dashboard |
@payloadcms/next | ^3.90.0 | Admin view + endpoint wiring |
@tanstack/react-query | ^5.59.0 | Data fetching/caching in the dashboard |
lucide-react | ^0.469.0 | Icons (KPIs, lead-action registry) |
react-day-picker | ^9.0.0 | Date-range picker in the filter bar |
recharts | ^2.15.0 | Trend / donut charts |
next | ^14 || ^15 | Optional — only for the client tracking half |
react / react-dom | ^18 || ^19 | Optional — only for the client tracking half |
next, react, and react-dom are declared optional, but any real Payload v3 + Next.js app already provides them.
@focus-reactive/payload-plugin-guard is a dependency of the plugin; install it in the project too, because the project imports withAccessPolicy and the policy helpers from it.
The plugin runs on @focus-reactive/payload-plugin-guard, and the project decides who may see what in its access policy file.
Add an entry for the plugin, with one gate per capability:
// src/access.policy.ts
import { defineAccessPolicy, gate } from "@focus-reactive/payload-plugin-guard";
const hasRole = (...roles: string[]) =>
gate(({ req }) => req.user?.collection === "users" && roles.includes(req.user.role));
export const accessPolicy = defineAccessPolicy({
// ...collections, globals and the other plugins of the project
plugins: {
analytics: {
viewAnalytics: hasRole("admin", "marketing"),
viewSessions: hasRole("admin"),
viewAbResults: hasRole("admin", "marketing"),
},
},
});
There is no default: without the access option the plugin refuses to start.
See Access and capabilities for what each capability allows.
// payload.config.ts
import { buildConfig } from "payload";
import { withAccessPolicy } from "@focus-reactive/payload-plugin-guard";
import { analyticsPlugin } from "@focus-reactive/payload-plugin-analytics";
import { accessPolicy } from "./access.policy";
export default withAccessPolicy(accessPolicy, buildConfig({
plugins: [
analyticsPlugin({
access: accessPolicy.plugins.analytics,
ga4: {
measurementId: process.env.GA4_MEASUREMENT_ID!, // G-XXXXXXX
propertyId: process.env.GA4_PROPERTY_ID!, // numeric
serviceAccount: {
clientEmail: process.env.GA4_CLIENT_EMAIL!,
privateKey: (process.env.GA4_PRIVATE_KEY ?? "").replace(/\\n/g, "\n"),
},
},
leadActions: {
types: ["phone_click", "email_click", "form_submit"],
},
}),
],
}));
This injects, with no further admin configuration:
/admin/analyticsviewAnalytics/api/analytics/*ga4Provider() returns a provider object, so the wrapper must be a Client Component. Create it once and mount it at the root of your app:
// app/AnalyticsProviderClient.tsx
"use client";
import { AnalyticsProvider, ga4Provider } from "@focus-reactive/payload-plugin-analytics/client";
import type { ReactNode } from "react";
export function AnalyticsProviderClient({ measurementId, children }: { measurementId: string; children: ReactNode }) {
return <AnalyticsProvider provider={ga4Provider({ measurementId })}>{children}</AnalyticsProvider>;
}
// app/layout.tsx (Server Component)
import { AnalyticsProviderClient } from "./AnalyticsProviderClient";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<AnalyticsProviderClient measurementId={process.env.NEXT_PUBLIC_GA4_MEASUREMENT_ID!}>
<main>{children}</main>
</AnalyticsProviderClient>
</body>
</html>
);
}
page_view now fires automatically on first load and on every client-side route change.
Start your app, sign into the Payload admin, and click the chart icon in the header (or visit /admin/analytics). Pick a date range and comparison in the filter bar. Data appears once GA4 has collected events and the service account has property access.
interface AnalyticsPluginConfig {
/** One gate per capability, usually `accessPolicy.plugins.analytics`. Required, no default. */
access: { viewAnalytics: Gate; viewSessions: Gate; viewAbResults: Gate };
/** GA4 connection — required. */
ga4: Ga4Config;
/** Skip the plugin entirely (returns the config untouched). */
disabled?: boolean;
/** Lead-action types + admin icon/label registry. */
leadActions?: LeadActionsPluginConfig;
/** Auto-attach DOM listeners on the client for common lead actions. */
autoTrackLeadActions?: AutoTrackLeadActionsConfig;
/** Override / extend i18n strings used by the dashboard. */
translations?: Translations;
/** Register custom dashboard blocks (component + optional server fetch). */
blocks?: Record<BlockId, Partial<BlockDefinition>>;
/** Reorder, resize, enable/disable, or add rows & blocks per tab. */
layout?: AnalyticsLayoutConfigInput;
/** Enable the A/B analytics tab (integrates with payload-plugin-ab). */
ab?: AbIntegrationConfig;
/** Report by CMS page instead of by URL path, for the pages the user may read. */
pages?: PagesAnalyticsConfig;
}
interface PagesAnalyticsConfig {
/** Collections whose documents are public pages. A string means { slug, publishedOnly: true }. */
collections: Array<string | { slug: string; publishedOnly?: boolean; titleField?: string }>;
/** Stable refs for routes that are not CMS documents, such as "__home"; every user sees them. */
syntheticRefs?: string[];
/** GA4 custom dimension names. */
dimensions?: { pageRef?: string; contentLocale?: string };
/** Display path of a page ref; called only for synthetic refs and pages the user may read. */
resolvePagePath?: (ref: string, req: PayloadRequest) => string | Promise<string>;
}
Read documents in resolvePagePath with overrideAccess: false and the req it receives, so a path is resolved with the user's own rights.
interface Ga4Config {
/** GA4 numeric Property ID — used by the Data API (server reports). */
propertyId: string;
/** GA4 Measurement ID (G-XXXXXXX) — used by gtag.js (client events). */
measurementId: string;
serviceAccount: {
clientEmail: string;
privateKey: string; // real multi-line PEM at runtime
};
}
Validation at buildConfig time: measurementId must match ^G-[A-Z0-9]+$, propertyId and the service-account credentials are required. If any of them is missing or invalid, a warning is logged and the data endpoints are not registered. The admin view and header link stay registered but hidden (the view answers 404), so payload generate:importmap produces the same import map with or without the GA4 env vars. disabled: true skips the plugin entirely.
interface LeadActionsPluginConfig {
/** Lead-action type identifiers your front end fires (e.g. 'phone_click'). */
types?: string[];
/** Import path to a default-exported lead-action registry component
* (see "Lead Actions" → admin icons). e.g. '@/lead-actions-admin#default' */
adminRegistry?: string;
}
interface AutoTrackLeadActionsConfig {
phoneClicks?: boolean; // tel: links
emailClicks?: boolean; // mailto: links
directionsClicks?: boolean; // map / directions links
whatsappClicks?: boolean;
telegramClicks?: boolean;
formSubmits?: boolean;
}
Passed to <AnalyticsProvider autoTrackLeadActions={...}> on the client; the plugin attaches DOM listeners that fire the matching lead_action events without per-element markup.
All client exports come from @focus-reactive/payload-plugin-analytics/client.
<AnalyticsProvider>Mount once at the app root. Injects the provider's scripts (gtag.js), tracks route changes, and wires the lead-action registry.
<AnalyticsProvider
provider={ga4Provider({ measurementId })}
leadActionTypes={["phone_click", "cta_pricing_click"]} // optional
autoTrackLeadActions={{ phoneClicks: true, formSubmits: true }} // optional
trackRouteChanges // default: true
>
{children}
</AnalyticsProvider>
| Prop | Type | Default | Description |
|---|---|---|---|
provider | AnalyticsProvider adapter | — | Usually ga4Provider({ measurementId }) |
leadActionTypes | string[] | — | Lead-action types available on the client |
autoTrackLeadActions | AutoTrackLeadActionsConfig | — | Auto-attach DOM listeners for common lead actions |
trackRouteChanges | boolean | true | Fire page_view on Next.js client navigation |
Mount it once. A nested
<AnalyticsProvider>logs a dev warning and causes duplicatepage_viewevents.
ga4Providerimport { ga4Provider } from "@focus-reactive/payload-plugin-analytics/client";
const provider = ga4Provider({ measurementId: "G-XXXXXXX" });
Returns an AnalyticsProvider adapter that loads gtag.js, pushes events to the GA4 dataLayer, and reports page views (with title + URL). The adapter interface is small — implement it yourself to target a different backend:
interface AnalyticsProvider {
readonly name: string;
Scripts: () => ReactNode;
trackEvent: (name: string, payload?: Record<string, unknown>) => void;
pageView: (path: string) => void;
}
<Track> — declarative eventsWraps a single child element and fires an event on an interaction. It merges with the child's existing handler, so your onClick/onSubmit still runs.
import { Track } from "@focus-reactive/payload-plugin-analytics/client";
<Track on="click" event="cta_click" payload={{ location: "hero" }}>
<button onClick={doThing}>Get started</button>
</Track>;
on accepts "click" | "submit" | "view" | "hover". on="view" fires once when the element scrolls into view.
<TrackLeadAction> — conversion eventsA thin wrapper over <Track> that fires the lead_action event with fr_lead_type set to type.
import { TrackLeadAction } from "@focus-reactive/payload-plugin-analytics/client";
<TrackLeadAction on="click" type="phone_click">
<a href="tel:+1234567890">Call us</a>
</TrackLeadAction>;
useAnalytics() — imperative APIimport { useAnalytics } from "@focus-reactive/payload-plugin-analytics/client";
function ContactForm() {
const { track, trackLeadAction, pageView } = useAnalytics();
return (
<form
onSubmit={() => {
trackLeadAction("form_submit", { form: "contact" });
}}>
{/* ... */}
</form>
);
}
| Method | Fires |
|---|---|
track(event, payload?) | A custom GA4 event |
trackLeadAction(type, p?) | lead_action with fr_lead_type = type |
pageView(path) | A manual page_view (rarely needed — route changes auto-fire) |
The plugin exports the GA4 event-name constants it relies on:
import {
TRAFFIC_EVENTS, // page_view, session_start, first_visit, user_engagement
ENGAGEMENT_EVENTS, // scroll, click, form_start, form_submit, video_start, ...
LEAD_ACTION_EVENT_NAME, // 'lead_action'
FR_LEAD_TYPE_PARAM, // 'fr_lead_type'
BUILT_IN_LEAD_ACTION_TYPES,
} from "@focus-reactive/payload-plugin-analytics/client";
Lead actions are the conversions the dashboard's Lead Actions tab measures. They're all the same GA4 event — lead_action — distinguished by the fr_lead_type parameter.
phone_click · email_click · directions_click · whatsapp_click
telegram_click · website_click · booking_click · form_submit
Declare your own types in plugin config (so the dashboard knows to query them) and fire them from the client:
// payload.config.ts
analyticsPlugin({
ga4: {
/* ... */
},
leadActions: {
types: ["phone_click", "email_click", "form_submit", "cta_pricing_click"],
},
});
<TrackLeadAction on="click" type="cta_pricing_click">
<button>See pricing</button>
</TrackLeadAction>
Unknown types still render in the dashboard with a humanized label and a fallback icon.
| Approach | Use when |
|---|---|
<TrackLeadAction> | You control the element and want declarative markup |
useAnalytics().trackLeadAction() | You fire from a handler / effect |
autoTrackLeadActions | Common patterns (tel:, mailto:, form submits) site-wide |
Auto-tracking respects an opt-out: add data-analytics-skip to any element you don't want auto-tracked.
Customize how lead-action types render in the dashboard (icon + label) with a registry. Create a client module that default-exports a registry component:
// lead-actions-admin.tsx
"use client";
import { createLeadActionRegistry } from "@focus-reactive/payload-plugin-analytics/client";
import { Zap } from "lucide-react";
export default createLeadActionRegistry({
cta_pricing_click: { icon: Zap, label: "Pricing CTA" },
});
Then point leadActions.adminRegistry at it (Payload component-path syntax):
analyticsPlugin({
ga4: {
/* ... */
},
leadActions: {
types: ["cta_pricing_click"],
adminRegistry: "@/lead-actions-admin#default",
},
});
Your entries are merged over the built-in registry, so you only declare what you want to override.
The dashboard has three built-in tabs:
| Tab | Built-in blocks |
|---|---|
overview | sessions-kpi, users-kpi, pageviews-kpi, bounce-rate-kpi, avg-duration-kpi, trend-chart, top-pages, top-sources, top-events, devices-donut, top-countries |
lead-actions | total-leads-kpi, conversion-rate-kpi, avg-time-kpi, lead-actions-by-type, per-page-breakdown, discovery-paths |
sessions | Session list + per-session event drawer |
The layout option lets you override placement per tab → row → block. Each block placement takes order, colSpan, and enabled; each row takes order, columns, and enabled.
analyticsPlugin({
ga4: {
/* ... */
},
layout: {
tabs: {
overview: {
rows: {
"kpi-row": {
columns: 4,
blocks: {
"bounce-rate-kpi": { enabled: false }, // hide a block
"sessions-kpi": { order: 0, colSpan: 1 }, // reposition / resize
},
},
},
},
},
},
});
Built-in row IDs: overview → kpi-row, trend-row, top-row, devices-countries-row; lead-actions → kpi-row, by-type-row, per-page-row, journeys-row.
Register your own block with a React component and an optional server-side fetch that runs against a property-scoped GA4 client. Place it in the layout like any built-in block.
// payload.config.ts
import type { BlockFetchArgs } from "@focus-reactive/payload-plugin-analytics";
analyticsPlugin({
ga4: {
/* ... */
},
blocks: {
"my-metric": {
component: "@/blocks/MyMetric#default", // client component path
fetch: async ({ dateRange, comparison, ga4, req }: BlockFetchArgs) => {
const report = await ga4.runReport({
/* GA4 Data API request */
});
return shapeForUi(report);
},
},
},
layout: {
tabs: {
overview: {
rows: {
"top-row": { blocks: { "my-metric": { order: 0, colSpan: 2 } } },
},
},
},
},
});
The server result is fetched via /api/analytics/custom/my-metric and handed to your component as data.
The endpoint needs viewAnalytics.
If fetch reads Payload data, pass req and overrideAccess: false to the Local API, so it returns only what the user may read.
interface BlockComponentProps<TData = unknown> {
data?: TData;
loading?: boolean;
error?: Error;
dateRange: DateRange;
comparison: Comparison;
colSpan: number;
t: (key: string) => string;
className?: string;
}
To match the built-in look, import the dashboard's UI primitives and query hooks from the /client/blocks entry:
import {
DataCard,
KpiCard,
BarList,
TopNTable,
DonutChart,
TrendChart,
SkeletonBlock,
ErrorTile,
useCustomBlockQuery,
} from "@focus-reactive/payload-plugin-analytics/client/blocks";
| Capability | Lets a user | Endpoints |
|---|---|---|
viewAnalytics | open the dashboard: Overview and Lead Actions tabs, journeys and custom blocks | kpis, top-pages, top-events, top-sources, top-devices, top-countries, lead-actions, journeys, custom/<block id> |
viewSessions | see the Sessions tab: each visitor's session and its events | sessions, sessions/:id |
viewAbResults | see the A/B tab | ab/kpis, ab/experiments, ab/experiment/* |
Every endpoint is a POST under /api/analytics/ that takes a JSON body.
The capability says who may call it at all; what a report shows also follows the user's own read rights:
pages, page reports cover only the pages the user may read in the configured collections, plus the syntheticRefs.
Page titles come from those pages, read with the user's rights, and resolvePagePath runs only for them.
A user who may read no page sees no page data, not the whole property.ab-experiments collection, so your policy's read for that collection decides.
An experiment the user may not read answers 404, before GA4 is queried.
Variant names and shares come from the variant pages the user may read.viewAnalytics.
The Sessions and A/B tabs are hidden for users without viewSessions or viewAbResults.
A link to a hidden tab (?tab=sessions, ?tab=ab) opens the Overview tab instead.Anonymous callers get 401; users of another auth collection and users without the capability get 403.
A body that is not application/json gets 415, and a body over 64 KiB gets 413.
Row limits are capped (limit at 100 for top lists, 250 for sessions; sampleLimit at 250 000 for journeys).
Each user may send 120 analytics requests a minute; past that the endpoints answer 429.
Errors carry a generic message; the GA4 error goes to the server log.
GET /api/analytics/capabilities answers a logged-in admin user with { "viewAnalytics": boolean, "viewSessions": boolean, "viewAbResults": boolean } for that user.
The plugin owns no collection or global.
page_path, page_location and page_referrer keep only campaign parameters of the query string: utm_source, utm_medium, utm_campaign, utm_term, utm_content, utm_id, gclid, gbraid, wbraid and dclid.
Other parameters and the fragment are dropped, because they can carry search terms, tokens or e-mail addresses.ga4Provider loads gtag only for a measurement id of the form G-XXXXXXX; for any other value it logs an error and loads nothing.When you pass an ab config, the dashboard gains an A/B tab that computes exposure, conversion rate, lift, statistical significance, sample-ratio-mismatch (SRM), and a portfolio win-rate. It reads the A/B plugin's ab-experiments collection plus the fr_ab_* GA4 dimensions.
This tab is designed to pair with @focus-reactive/payload-plugin-ab:
<ExperimentTracker> on variant-served pages — it stamps fr_ab_experiment, fr_ab_variant, and fr_ab_visitor_id on every GA4 event.analyticsPlugin({
ga4: {
/* ... */
},
ab: {}, // presence of the key turns the tab on
});
Conversions on the A/B tab are the same lead_action events as the rest of the dashboard — there's no separate AB conversion event.
The tab reads ab-experiments with the user's own rights, so give the roles that hold viewAbResults read access to it in your policy, for example "ab-experiments": { create: nobody, read: hasRole("admin", "marketing"), update: nobody, delete: nobody }.
An experiment record is followed only into a configured collection that has the A/B variant field, and only in a locale of the config.
interface AbIntegrationConfig {
/** Slug of the AB plugin's experiments collection. Default: 'ab-experiments'. */
experimentsCollectionSlug?: string;
/** Override the GA4 dimension parameter names (must match what the tracker stamps). */
dimensions?: { experiment?: string; variant?: string; visitorId?: string };
/** Significance / SRM tuning. */
stats?: {
alpha?: number; // significance threshold. default 0.05
power?: number; // statistical power (1 - beta). default 0.80
srmThreshold?: number; // SRM chi-square failure threshold. default 0.001
srmWindowDays?: number; // trailing window for the SRM check. default 7
};
/** Win-rate qualification. alpha/power inherited from `stats`. */
winRate?: {
mdeCeiling?: number; // qualifies when relative MDE ≤ this. default 0.20
sessionFloor?: number; // per-bucket session floor. default 100
};
/** Map the AB plugin's field names if you customized them. */
variantFields?: { variantOf?: string; passPercentage?: string; slug?: string; name?: string };
}
2.0 moves the plugin onto @focus-reactive/payload-plugin-guard; Upgrading to the guard explains the model all the plugins share, with a complete example.
Every access rule is now written by hand in your project's src/access.policy.ts, and nothing is open by default: an entry you leave out stops the boot, and a capability you do not grant is refused for everyone.
@payloadcms/* package 3.90 or later, with the React and Next versions Payload 3.90 requires, Node 22.22 or later, and @focus-reactive/payload-plugin-guard installed next to the plugin.access function is replaced by three capabilities, and the AccessFn type is gone.
There is no default: 1.x let any logged-in user of any auth collection in.
A former access: ({ req }) => ... rule becomes the viewAnalytics gate; decide separately who gets viewSessions and viewAbResults.ab-experiments with the user's own rights, so the roles with viewAbResults need read access to it in the policy.pages, page reports cover only the pages the user may read; check that the read rules of your page collections let the analytics roles read the pages they should report on.
In resolvePagePath, replace overrideAccess: true with overrideAccess: false and pass req./api/analytics/ are unchanged, but they refuse bodies that are not application/json, cap their row limits, allow 120 requests a minute per user, and answer errors with a generic message.page_path, page_location and page_referrer, so GA4 reports that grouped by full query strings see them collapse.ga4Provider loads nothing for a measurement id that is not of the form G-XXXXXXX.Upgrade payload and every @payloadcms/* package to 3.90 or later, run the server on Node 22.22 or later, and install the guard:
pnpm add @focus-reactive/payload-plugin-guard @focus-reactive/payload-plugin-analytics.
Add the plugin's entries to src/access.policy.ts, with gates for your own roles; if the project has no policy file yet, write it first as the guide describes.
// src/access.policy.ts, inside defineAccessPolicy({ ... })
plugins: {
analytics: {
viewAnalytics: isMarketer,
viewSessions: isAdmin,
viewAbResults: isMarketer,
},
},
viewAnalytics: open the dashboard: the Overview and Lead Actions tabs, journeys and custom blocks.viewSessions: see the Sessions tab, each visitor's sessions and their events.viewAbResults: see the A/B tab, limited to the experiments the user may read in ab-experiments.Pass access: accessPolicy.plugins.analytics to analyticsPlugin, and export the config wrapped: export default withAccessPolicy(accessPolicy, buildConfig({ ... })).
Database: no migration; the plugin owns no collection or global.
Re-test: an anonymous POST /api/analytics/kpis answers 401, a user without viewAnalytics gets 403 and a 404 for the admin view, and a user without viewSessions gets 403 from POST /api/analytics/sessions; then open the dashboard as each analytics role and check that page reports list only the pages that role may read.
| Import path | Exports |
|---|---|
@focus-reactive/payload-plugin-analytics | analyticsPlugin; config types (AnalyticsPluginConfig, Ga4Config, AutoTrackLeadActionsConfig, AbIntegrationConfig, LeadActionsPluginConfig, …); query/response types; layout types (BlockDefinition, BlockFetchArgs, BlockComponentProps, AnalyticsLayoutConfigInput, …); event + endpoint constants (TRAFFIC_EVENTS, ENGAGEMENT_EVENTS, LEAD_ACTION_EVENT_NAME, ANALYTICS_ENDPOINT_PATHS, layout BUILTIN_* ids) |
@focus-reactive/payload-plugin-analytics/client | AnalyticsProvider, ga4Provider, Track, TrackLeadAction, useAnalytics, useLeadActionTypes, createLeadActionRegistry, LeadActionRegistryProvider, useLeadActionRegistry, event constants + types |
@focus-reactive/payload-plugin-analytics/client/blocks | UI primitives for custom blocks: DataCard, KpiCard, BarList, TopNTable, DonutChart, TrendChart, SkeletonBlock, ErrorTile, EmptyTile, SetupRequiredCard; hooks useCustomBlockQuery, useSessionsQuery, useSessionDetailQuery |
@focus-reactive/payload-plugin-analytics/components/AnalyticsView | The dashboard view component (auto-registered by the plugin) |
@focus-reactive/payload-plugin-analytics/components/AnalyticsView/AnalyticsHeaderLink | The admin header link component (auto-registered by the plugin) |
@focus-reactive/payload-plugin-analytics/components/AnalyticsView/AnalyticsHeaderAction | Server wrapper that renders the header link for users with viewAnalytics (auto-registered) |
@focus-reactive/payload-plugin-analytics/admin.css | Dashboard stylesheet (the view imports it itself; exposed for manual control) |
MIT © FocusReactive
Topics
Tags
payload plugin ab
A/B testing with page variants managed in the Payload admin and routed by Next.js middleware at the edge
741.0k/wk37v3
payload plugin presets
Save and apply reusable block configurations as presets from the Payload admin blocks drawer
786.7k/wk37v3
payload plugin scheduling
Schedule future publication of drafts on collections and globals with a secured cron endpoint
77783/wk37v3
payload plugin audit log
Append-only audit log of document, global and auth changes with CSV and NDJSON export
72394/wk37v3
payload plugin ga4 ecommerce
GA4 reporting dashboards and per-record analytics tabs inside the Payload admin panel
44115/wk10v3
payload plugin comments
Document-level and field-level comments with mentions, resolution and email notifications for Payload admin
757.0k/wk37v3