focusreactive

payload plugin analytics

by focusreactive
payload-plugins
Analytics
v3
^3.90.0
MIT

Overview

Summary generated from the README

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.

Features

  • Admin dashboard with KPIs, top pages, sources, events, devices and geography
  • Sessions tab and journeys built from event-scoped GA4 custom dimensions
  • Lead-action conversion tracking with optional automatic listeners for phone, email and form events
  • Client provider tracking page views on first load and every route change
  • Optional A/B results tab that integrates with the companion A/B plugin
  • Capability-based access for dashboard, sessions and A/B results, with no default access

Use cases

  • Show marketing teams GA4 traffic and conversion reports without leaving the Payload admin
  • Track phone, email and form lead actions on a Next.js site and review them by type
  • Report analytics by CMS page for only the pages a given editor may read

Installation

npm i @focus-reactive/payload-plugin-analytics

37

Stars

5

Forks

33

Open Issues

Today

Last Updated

821

Weekly Downloads

v2.0.1

npm Version

1.5 MB

Unpacked Size

6

Dependencies

Repository stars

37+22 since Sep 7

Show data
Repository stars by day (UTC)
DateStars
Dec 6, 202637
Dec 5, 202637
Dec 4, 202637
Dec 3, 202637
Dec 2, 202637
Dec 1, 202636
Nov 30, 202635
Nov 29, 202635
Nov 28, 202634
Nov 27, 202634
Nov 26, 202634
Nov 25, 202634
Nov 24, 202634
Nov 23, 202634
Nov 22, 202634
Nov 21, 202634
Nov 20, 202633
Nov 19, 202632
Nov 18, 202632
Nov 17, 202632
Nov 16, 202632
Nov 15, 202632
Nov 14, 202632
Nov 13, 202632
Nov 12, 202632
Nov 11, 202632
Nov 10, 202632
Nov 9, 202631
Nov 8, 202631
Nov 7, 202631
Nov 6, 202631
Nov 5, 202631
Nov 4, 202630
Nov 3, 202630
Nov 2, 202630
Nov 1, 202630
Oct 31, 202630
Oct 30, 202630
Oct 29, 202630
Oct 28, 202630
Oct 27, 202630
Oct 26, 202630
Oct 25, 202630
Oct 24, 202629
Oct 23, 202629
Oct 22, 202629
Oct 21, 202629
Oct 20, 202629
Oct 19, 202629
Oct 18, 202629
Oct 17, 202627
Oct 16, 202626
Oct 15, 202626
Oct 14, 202626
Oct 13, 202625
Oct 12, 202625
Oct 11, 202625
Oct 10, 202625
Oct 9, 202625
Oct 8, 202625
Oct 7, 202625
Oct 6, 202624
Oct 5, 202624
Oct 4, 202624
Oct 3, 202623
Oct 2, 202622
Oct 1, 202622
Sep 30, 202620
Sep 29, 202620
Sep 28, 202620
Sep 27, 202620
Sep 26, 202619
Sep 25, 202618
Sep 24, 202618
Sep 23, 202618
Sep 22, 202618
Sep 21, 202618
Sep 20, 202618
Sep 19, 202618
Sep 18, 202618
Sep 17, 202618
Sep 16, 202618
Sep 15, 202618
Sep 14, 202618
Sep 13, 202617
Sep 12, 202617
Sep 11, 202617
Sep 10, 202616
Sep 9, 202616
Sep 8, 202616
Sep 7, 202615

Shared by 15 plugins in focusreactive/payload-plugins.

npm weekly downloads

635+543 since Sep 7

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 6, 2026635
Dec 5, 2026708
Dec 4, 2026736
Dec 3, 2026800
Dec 2, 2026756
Dec 1, 2026714
Nov 30, 2026702
Nov 29, 2026552
Nov 28, 2026472
Nov 27, 2026486
Nov 26, 2026465
Nov 25, 2026468
Nov 24, 2026512
Nov 23, 2026576
Nov 22, 2026626
Nov 21, 2026737
Nov 20, 2026705
Nov 19, 2026676
Nov 18, 2026757
Nov 17, 2026727
Nov 16, 2026658
Nov 15, 2026723
Nov 14, 2026759
Nov 13, 2026758
Nov 12, 2026772
Nov 11, 2026825
Nov 10, 2026858
Nov 9, 2026965
Nov 8, 2026909
Nov 7, 2026827
Nov 6, 2026795
Nov 5, 2026773
Nov 4, 2026602
Nov 3, 2026606
Nov 2, 2026688
Nov 1, 2026664
Oct 31, 2026617
Oct 30, 2026613
Oct 29, 2026516
Oct 28, 2026467
Oct 27, 2026432
Oct 26, 2026254
Oct 25, 2026203
Oct 24, 2026165
Oct 23, 2026104
Oct 22, 2026149
Oct 21, 2026226
Oct 20, 2026219
Oct 19, 2026239
Oct 18, 2026342
Oct 17, 2026460
Oct 16, 2026613
Oct 15, 2026734
Oct 14, 2026763
Oct 13, 2026768
Oct 12, 2026734
Oct 11, 2026708
Oct 10, 2026589
Oct 9, 2026452
Oct 8, 2026313
Oct 7, 2026277
Oct 6, 2026290
Oct 5, 2026615
Oct 4, 2026598
Oct 3, 2026800
Oct 2, 2026852
Oct 1, 2026974
Sep 30, 2026990
Sep 29, 20261,002
Sep 28, 2026683
Sep 27, 2026705
Sep 26, 2026614
Sep 25, 2026655
Sep 24, 2026562
Sep 23, 2026512
Sep 22, 2026526
Sep 21, 2026565
Sep 20, 2026485
Sep 19, 2026468
Sep 18, 2026382
Sep 17, 2026421
Sep 16, 2026491
Sep 15, 2026521
Sep 14, 2026540
Sep 13, 2026520
Sep 12, 2026418
Sep 11, 2026405
Sep 10, 2026321
Sep 9, 2026241
Sep 8, 2026164
Sep 7, 202692

Each point is npm's rolling 7-day download count.

Health Score

70/100Good

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1177993877-payload-plugin-analytics.svg)](https://payloaddirectory.dev/plugins/1177993877-payload-plugin-analytics)
HTML
<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>
Updated Dec 5, 2026Created Mar 10, 2026Published Dec 4, 2026

README

@focus-reactive/payload-plugin-analytics

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:

  • Server — analyticsPlugin() registers an admin dashboard view and REST endpoints that read your data from the GA4 Data API using a service account.
  • Client — <AnalyticsProvider> + ga4Provider() load gtag.js, track page views and route changes, and fire engagement / lead-action events to GA4.

AI Integration Prompt

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).

How It Works

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.


GA4 Setup

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.

1. Get your GA4 identifiers

  • Measurement ID — G-XXXXXXX. GA4 → Admin → Data Streams → your web stream.
  • Property ID — the numeric ID (e.g. 123456789). GA4 → Admin → Property Settings.

2. Create a service account for the Data API

  1. In Google Cloud Console, create (or pick) a project.
  2. Enable the Google Analytics Data API.
  3. Create a Service Account → add a JSON key. From the key file you need client_email and private_key.

3. Grant the service account access to the GA4 property

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.

4. Register custom dimensions and the conversion event

GA4 → Admin → Custom definitions → Create custom dimension (scope = Event):

Parameter nameScopeRequired for
fr_session_idEventSessions tab and Session drawer (session identity)
fr_session_startEventSession start time / session ordering
fr_event_seqEventWithin-minute event ordering in journeys and drawer
fr_lead_typeEventLead Actions tab
fr_ab_experimentEventA/B tab (optional)
fr_ab_variantEventA/B tab (optional)
fr_ab_visitor_idEventA/B tab (optional)

Then create the matching custom metric under the same Custom definitions screen → Create custom metric (scope = Event):

Parameter nameScopeUnit / TypeRequired for
fr_elapsed_msEventStandard (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.

5. Provide the values to the plugin

# .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 \n sequences. Un-escape them before passing to the plugin: privateKey: process.env.GA4_PRIVATE_KEY!.replace(/\\n/g, '\n').


Installation

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 dependencyRangeWhy
payload^3.90.0Core - the plugin targets Payload v3
@payloadcms/ui^3.90.0Admin UI primitives used by the dashboard
@payloadcms/next^3.90.0Admin view + endpoint wiring
@tanstack/react-query^5.59.0Data fetching/caching in the dashboard
lucide-react^0.469.0Icons (KPIs, lead-action registry)
react-day-picker^9.0.0Date-range picker in the filter bar
recharts^2.15.0Trend / donut charts
next^14 || ^15Optional — only for the client tracking half
react / react-dom^18 || ^19Optional — 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.


Quick Start

Step 1: Grant the plugin's capabilities in your access policy

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.

Step 2: Register the plugin (server)

// 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:

  • An Analytics view at /admin/analytics
  • A chart icon in the admin header (tooltip "Analytics") linking to the view, shown only to users with viewAnalytics
  • Endpoints under /api/analytics/*
  • The admin providers needed by the dashboard

Step 3: Wrap your front end with the provider

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.

Step 4: Open the dashboard

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.


Configuration Reference

Plugin Options

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.

Ga4Config

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.

LeadActionsPluginConfig

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;
}

AutoTrackLeadActionsConfig

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.


Client Tracking

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>
PropTypeDefaultDescription
providerAnalyticsProvider adapter—Usually ga4Provider({ measurementId })
leadActionTypesstring[]—Lead-action types available on the client
autoTrackLeadActionsAutoTrackLeadActionsConfig—Auto-attach DOM listeners for common lead actions
trackRouteChangesbooleantrueFire page_view on Next.js client navigation

Mount it once. A nested <AnalyticsProvider> logs a dev warning and causes duplicate page_view events.

ga4Provider

import { 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 events

Wraps 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 events

A 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 API

import { useAnalytics } from "@focus-reactive/payload-plugin-analytics/client";

function ContactForm() {
  const { track, trackLeadAction, pageView } = useAnalytics();

  return (
    <form
      onSubmit={() => {
        trackLeadAction("form_submit", { form: "contact" });
      }}>
      {/* ... */}
    </form>
  );
}
MethodFires
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)

Event names

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

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.

Built-in types

phone_click · email_click · directions_click · whatsapp_click
telegram_click · website_click · booking_click · form_submit

Custom types

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.

Firing options

ApproachUse when
<TrackLeadAction>You control the element and want declarative markup
useAnalytics().trackLeadAction()You fire from a handler / effect
autoTrackLeadActionsCommon 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.

Admin icons & labels

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.


Dashboard & Layout Customization

The dashboard has three built-in tabs:

TabBuilt-in blocks
overviewsessions-kpi, users-kpi, pageviews-kpi, bounce-rate-kpi, avg-duration-kpi, trend-chart, top-pages, top-sources, top-events, devices-donut, top-countries
lead-actionstotal-leads-kpi, conversion-rate-kpi, avg-time-kpi, lead-actions-by-type, per-page-breakdown, discovery-paths
sessionsSession list + per-session event drawer

Reorder, resize, hide

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.

Custom blocks

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";

Access and capabilities

CapabilityLets a userEndpoints
viewAnalyticsopen the dashboard: Overview and Lead Actions tabs, journeys and custom blockskpis, top-pages, top-events, top-sources, top-devices, top-countries, lead-actions, journeys, custom/<block id>
viewSessionssee the Sessions tab: each visitor's session and its eventssessions, sessions/:id
viewAbResultssee the A/B tabab/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:

  • With 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.
  • The A/B tab lists only the experiments the user may read in the A/B plugin's 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.
  • The admin view answers 404, and the chart icon in the header is hidden, for users without 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.

What the tracking sends to GA4

  • 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.

A/B Tab

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:

  1. Run A/B tests with the AB plugin and mount its <ExperimentTracker> on variant-served pages — it stamps fr_ab_experiment, fr_ab_variant, and fr_ab_visitor_id on every GA4 event.
  2. Register those three dimensions in GA4 (see GA4 Setup).
  3. Enable the tab here:
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.

AbIntegrationConfig

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 };
}

Migrating from 1.x

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.

What changes

  • Payload and every @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.
  • The 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.
  • The A/B tab reads ab-experiments with the user's own rights, so the roles with viewAbResults need read access to it in the policy.
  • With 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.
  • The endpoint paths under /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.
  • The tracking keeps only campaign parameters of the query string in 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.

Steps

  1. 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.

  2. 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.
  3. Pass access: accessPolicy.plugins.analytics to analyticsPlugin, and export the config wrapped: export default withAccessPolicy(accessPolicy, buildConfig({ ... })).

  4. Database: no migration; the plugin owns no collection or global.

  5. 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.


Exports Reference

Import pathExports
@focus-reactive/payload-plugin-analyticsanalyticsPlugin; 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/clientAnalyticsProvider, ga4Provider, Track, TrackLeadAction, useAnalytics, useLeadActionTypes, createLeadActionRegistry, LeadActionRegistryProvider, useLeadActionRegistry, event constants + types
@focus-reactive/payload-plugin-analytics/client/blocksUI primitives for custom blocks: DataCard, KpiCard, BarList, TopNTable, DonutChart, TrendChart, SkeletonBlock, ErrorTile, EmptyTile, SetupRequiredCard; hooks useCustomBlockQuery, useSessionsQuery, useSessionDetailQuery
@focus-reactive/payload-plugin-analytics/components/AnalyticsViewThe dashboard view component (auto-registered by the plugin)
@focus-reactive/payload-plugin-analytics/components/AnalyticsView/AnalyticsHeaderLinkThe admin header link component (auto-registered by the plugin)
@focus-reactive/payload-plugin-analytics/components/AnalyticsView/AnalyticsHeaderActionServer wrapper that renders the header link for users with viewAnalytics (auto-registered)
@focus-reactive/payload-plugin-analytics/admin.cssDashboard stylesheet (the view imports it itself; exposed for manual control)

License

MIT © FocusReactive

Similar plugins