Installs Google Tag Manager and optionally GA4 on your site and discovers dataLayer events from browser runtime capture, GTM container scans and page crawls. Discovered events are stored in an editable registry in the Payload admin that serves as a tracking plan. It adds a settings global, REST endpoints, a scan job and React and browser helpers. Requires Payload 3.80 or newer.
Google Tag Manager for Payload CMS v3 with automatic dataLayer event discovery (runtime capture, container scan, page crawl) and an editable event registry.
Installation
npm i payload-plugin-gtm0
Stars
1
Forks
0
Open Issues
1 months ago
Last Updated
31
Weekly Downloads
v0.3.0
npm Version
538.3 KB
Unpacked Size
0
Dependencies
00 since Nov 1
| Date | Stars |
|---|---|
| Dec 6, 2026 | 0 |
| Dec 5, 2026 | 0 |
| Dec 4, 2026 | 0 |
| Dec 3, 2026 | 0 |
| Dec 2, 2026 | 0 |
| Dec 1, 2026 | 0 |
| Nov 30, 2026 | 0 |
| Nov 29, 2026 | 0 |
| Nov 28, 2026 | 0 |
| Nov 27, 2026 | 0 |
| Nov 26, 2026 | 0 |
| Nov 25, 2026 | 0 |
| Nov 24, 2026 | 0 |
| Nov 23, 2026 | 0 |
| Nov 22, 2026 | 0 |
| Nov 21, 2026 | 0 |
| Nov 20, 2026 | 0 |
| Nov 19, 2026 | 0 |
| Nov 18, 2026 | 0 |
| Nov 17, 2026 | 0 |
| Nov 16, 2026 | 0 |
| Nov 15, 2026 | 0 |
| Nov 14, 2026 | 0 |
| Nov 13, 2026 | 0 |
| Nov 12, 2026 | 0 |
| Nov 11, 2026 | 0 |
| Nov 10, 2026 | 0 |
| Nov 9, 2026 | 0 |
| Nov 8, 2026 | 0 |
| Nov 7, 2026 | 0 |
| Nov 6, 2026 | 0 |
| Nov 5, 2026 | 0 |
| Nov 4, 2026 | 0 |
| Nov 3, 2026 | 0 |
| Nov 2, 2026 | 0 |
| Nov 1, 2026 | 0 |
16+16 since Nov 6
| Date | Weekly downloads |
|---|---|
| Dec 6, 2026 | 16 |
| Dec 5, 2026 | 13 |
| Dec 4, 2026 | 24 |
| Dec 3, 2026 | 25 |
| Dec 2, 2026 | 28 |
| Dec 1, 2026 | 35 |
| Nov 30, 2026 | 31 |
| Nov 29, 2026 | 31 |
| Nov 28, 2026 | 38 |
| Nov 27, 2026 | 28 |
| Nov 26, 2026 | 40 |
| Nov 25, 2026 | 45 |
| Nov 24, 2026 | 39 |
| Nov 23, 2026 | 39 |
| Nov 22, 2026 | 42 |
| Nov 21, 2026 | 49 |
| Nov 20, 2026 | 59 |
| Nov 19, 2026 | 53 |
| Nov 18, 2026 | 95 |
| Nov 17, 2026 | 107 |
| Nov 16, 2026 | 136 |
| Nov 15, 2026 | 155 |
| Nov 14, 2026 | 183 |
| Nov 13, 2026 | 954 |
| Nov 12, 2026 | 947 |
| Nov 11, 2026 | 895 |
| Nov 10, 2026 | 882 |
| Nov 9, 2026 | 852 |
| Nov 8, 2026 | 829 |
| Nov 7, 2026 | 785 |
| Nov 6, 2026 | 0 |
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/1445439774-root)<a href="https://payloaddirectory.dev/plugins/1445439774-root"><img src="https://payloaddirectory.dev/badge/1445439774-root.svg" alt="Payload Directory"></a>README
Google Tag Manager for Payload CMS v3, with automatic dataLayer event discovery.
The plugin installs GTM and/or Google Analytics 4 (gtag.js) on your site and finds every event your site emits. Those events go into an editable event registry in the Payload admin, which works as a living tracking plan.
Events are discovered from three sources, because none of them is complete on its own:
| Source | How | Finds |
|---|---|---|
| Runtime (browser) | Hooks window.dataLayer, including gtag('event', …), and reports each event's name and parameter schema | Everything real visitors trigger, with full parameter paths and types (ecommerce.items[].item_id: string) |
| GTM container (server) | Fetches your published gtm.js and parses it | Every Custom Event trigger (regex triggers expanded), the GA4/other tags each one fires, and all Data Layer Variables. No traffic needed |
| Page crawl (server) | Crawls same-origin pages and sitemap.xml, plus their scripts | dataLayer.push({event: …}) and gtag('event', …) literals in your code |
Privacy by default: parameter values are not stored. Only names, key paths and types are kept. Optional examples are redacted (emails, phone/card-like numbers, tokens) and truncated.
Design document: docs/architecture/payload-plugin-gtm-system-design.md
pnpm add payload-plugin-gtm
// payload.config.ts
import { gtmPlugin } from 'payload-plugin-gtm'
export default buildConfig({
// ...
plugins: [
gtmPlugin({
containerId: 'GTM-ABC1234', // optional default; editable in the admin
measurementId: 'G-ABC123XYZ9', // optional GA4 via gtag.js; editable in the admin
scanSchedule: '0 3 * * *', // optional: daily container scan via Payload jobs
}),
],
})
Then:
pnpm payload generate:importmap # registers the admin "Scan" panel
pnpm payload migrate:create gtm # Postgres/SQLite: creates the gtm-events / gtm-settings tables
React / Next.js
// app/(frontend)/layout.tsx
import { GoogleTagManager } from 'payload-plugin-gtm/react'
export default function Layout({ children }) {
return (
<html>
<body>
<GoogleTagManager serverUrl={process.env.NEXT_PUBLIC_PAYLOAD_URL} />
{children}
</body>
</html>
)
}
To skip the config request, resolve the config on the server instead:
import { getPayload } from 'payload'
import config from '@payload-config'
import { getGtmPublicConfig } from 'payload-plugin-gtm'
import { GoogleTagManager } from 'payload-plugin-gtm/react'
const payload = await getPayload({ config })
const gtm = await getGtmPublicConfig(payload)
// ...
<GoogleTagManager config={gtm} serverUrl={process.env.NEXT_PUBLIC_PAYLOAD_URL} />
Any framework / plain JS
import { initGtm } from 'payload-plugin-gtm/browser'
initGtm({ serverUrl: 'https://cms.example.com' })
The browser runtime is about 3.2 KB min+gzip. It never throws into your page, and it sends with fetch(keepalive) or sendBeacon on page hide.
Lower-level APIs: loadGtm(), loadGoogleAnalytics(), startDiscovery(), gtmScriptContent() / gtagScriptContent() (for SSR <script> tags), consentScriptContent(), gtmNoscriptUrl(), pushEvent(), gtagEvent(), applyConsentDefaults(), and updateConsent().
Set a GA4 measurement ID (G-…) in GTM Settings → Google Analytics 4 or with the measurementId option. The same <GoogleTagManager /> / initGtm() call then loads gtag.js too. You can use GA4 on its own, without a GTM container.
dataLayer, so discovery records gtag('event', …) calls in the event registry.gtagEvent('sign_up', { method: 'email' }). pushEvent() writes a plain { event } object that only GTM reads; gtag.js ignores it.loadAnalytics={false} (or loadAnalytics: false) when you render gtagScriptContent() yourself.containerId / measurementId plugin option fails at boot instead of silently loading nothing.GA4 sets cookies as soon as it loads. To wait for the visitor's choice, turn on GTM Settings → Consent Mode. The plugin then pushes gtag('consent', 'default', …) before GTM or GA4 load. The defaults are denied for analytics_storage, ad_storage, ad_user_data and ad_personalization, optionally limited to regions such as DE or US-CA, with a wait_for_update of 500 ms. Your banner then reports the decision:
import { updateConsent } from 'payload-plugin-gtm/browser' // or /react
onAccept(() => updateConsent({ analytics_storage: 'granted', ad_storage: 'granted' }))
consentDefaults={false} so the plugin doesn't override them.consentScriptContent(config.consent) in an inline <script> in <head>, before any tag, and pass consentDefaults={false}.shouldCapture if your policy requires it.Pass your nonce as nonce. It is set on the inline bootstrap and on the gtm.js / gtag/js script that the bootstrap loads. GA4 also needs these hosts:
script-src: https://www.googletagmanager.comconnect-src / img-src: https://*.google-analytics.com, https://*.analytics.google.com, https://www.googletagmanager.comEverything appears under Google Tag Manager in the admin sidebar:
status (discovered → approved / deprecated / ignored), description, owner, notes, and per-parameter descriptions. Discovery never overwrites these.
gtm_auth / gtm_preview), dataLayer name, discovery settings (enable, sample rate, built-in gtm.* events, example capture, allowed origins), and crawl settings (site URL, sitemap, extra URLs).| Method | Path | Access | Purpose |
|---|---|---|---|
| GET | /api/gtm/config | public | Runtime config for the website (cached 60 s) |
| POST | /api/gtm/collect | public | Discovery beacon: validated, rate limited, deduplicated |
| POST | /api/gtm/scan | access.scan | { container?: boolean, crawl?: boolean } |
| GET | /api/gtm/export | access.scan | Tracking plan JSON |
The job task gtmScan (input { crawl?: boolean }) is registered for scheduled or queued scans.
gtmPlugin({
containerId?: string // default container (the settings global overrides it)
measurementId?: string // default GA4 measurement ID, loaded with gtag.js (global overrides it)
disabled?: boolean // keeps the schema, removes endpoints, UI and job
collectionSlug?: string // 'gtm-events'
globalSlug?: string // 'gtm-settings'
basePath?: string // 'gtm' → /api/gtm/*; change it if adblockers block it
adminGroup?: string // 'Google Tag Manager'
access?: { read, update, delete, updateSettings, scan }
discovery?: {
maxEvents?: number // 500: registry cap (protects against spam and dynamic names)
maxNewEventsPerHour?: number // 100: new names from runtime/crawl per hour, across all instances
rateLimitPerMinute?: number // 30 per IP for the built-in (in-memory) limiter
rateLimiter?: { take(key, req): boolean | Promise<boolean> } // shared limiter, e.g. Redis
getClientIp?: (req) => string // how a client is identified for rate limiting
writeIntervalMs?: number // 300000: max one write per event per interval when nothing is new
dedupeWindowMs?: number // 60000: skip identical observations on this instance
}
crawl?: { maxPages?: 25, maxScripts?: 30, timeoutMs?: 10000 }
scanSchedule?: string // cron, e.g. '0 3 * * *'
scanQueue?: string // 'default'
cacheSeconds?: number // 30: settings cache
overrideCollection?: (c) => c // add fields, tenant scoping, hooks…
overrideGlobal?: (g) => g
})
Who can change the settings matters most. Anyone who can edit GTM Settings can load any GTM container, which means running any JavaScript on every page of your site. By default only logged-in users of the admin user collection (admin.user) can read or edit the plugin's data and run scans. Users of other auth collections, such as storefront customers, are refused. If your admin collection also holds non-admin users (a roles field with customer, editor, …), restrict it explicitly; the plugin logs a warning at boot when it sees a role field and no override:
const isAdmin = ({ req }) => Boolean(req.user?.roles?.includes('admin'))
gtmPlugin({ access: { updateSettings: isAdmin, scan: isAdmin, update: isAdmin, delete: isAdmin } })
Collect endpoint protections:
serverURL origin)REST create on the events collection is always denied. Events are created only by discovery.
Restricted outbound fetches. Container scans only fetch from https://www.googletagmanager.com. The crawl only fetches the configured site's origin; redirects are re-checked, and every fetch has timeouts and byte caps.
The crawler can reach any host the admin enters, including internal addresses. It stays on that one origin, but only trusted admins should be able to set the site URL (see above).
Client IP. The default uses cf-connecting-ip, then x-real-ip, then the last x-forwarded-for entry (the one your proxy added; the first is client-controlled). Override discovery.getClientIp if your setup differs.
The plugin's shared state lives in the database, so it is safe with any number of instances:
gtm-events-locks collection), so two requests can't overwrite each other's parameters or pages. This works the same on Postgres, SQLite and MongoDB.scan lease, so a schedule plus a manual click (or two instances running the job) don't scan twice. Leases expire on their own if an instance crashes.maxNewEventsPerHour), so junk posted to the public endpoint can't fill the registry quickly from any number of instances.writeIntervalMs per event, so steady traffic mostly costs a single read.What stays per instance: the built-in rate limiter, the dedupe window and the settings cache (cacheSeconds). For one global rate limit, pass a shared limiter:
import { Ratelimit } from '@upstash/ratelimit'
import { Redis } from '@upstash/redis'
const ratelimit = new Ratelimit({ limiter: Ratelimit.slidingWindow(30, '1 m'), redis: Redis.fromEnv() })
gtmPlugin({
discovery: {
rateLimiter: { take: async (ip) => (await ratelimit.limit(`gtm:${ip}`)).success },
},
})
If the shared limiter throws, the plugin falls back to the in-memory one instead of opening the endpoint up.
occurrences stays approximate: in-memory counts that haven't been written yet are lost if an instance stops. Use GA4 for real counts.
Upgrading from 0.1.x: this version adds the gtm-events-locks collection and an index on firstSeenAt. On Postgres or SQLite with migrations, run payload migrate:create and payload migrate after upgrading.
GET /api/gtm/config returns discovery.enabled: true./api/gtm/*. If it is, change basePath, and pass the same value to the frontend (<GoogleTagManager basePath="t" /> or initGtm({ basePath: 't' })). Do the same with apiRoute if you changed Payload's routes.api. Otherwise the site can't find its config and loads neither GTM nor GA4./config is cacheable for 60 s (plus up to 5 min stale-while-revalidate). Allow about 10 minutes, or render the config on the server with getGtmPublicConfig().gtmScan job (scanSchedule, or queue it with { crawl: true }), or lower crawl.maxPages / crawl.timeoutMs.gtm_auth/gtm_preview..*_error) can't be turned into a finite list of names. Runtime discovery will still record the actual events.The test suite covers the plugin's logic. These depend on your site and can only be checked there, on staging first:
access is restricted to admins if your admin user collection has non-admin roles (watch for the boot warning).payload migrate:create / migrate) for the new settings fields.GET /api/<basePath>/config returns your IDs, and the frontend uses the same basePath / apiRoute._ga cookies only appear after updateConsent(... 'granted').POST /collect from the site returns 202.discovery.rateLimiter is configured if you need a global limit.pnpm install
cp dev/.env.example dev/.env
pnpm dev # http://localhost:3000 (demo page) and /admin ([email protected] / test)
pnpm test # unit + browser (jsdom) + integration (Payload on SQLite)
pnpm typecheck
pnpm build
Compatibility: Payload ^3.80 (developed against 3.92.1), Node ≥ 20.9.
analytics
Event registry and consent-gated routing of analytics events to GTM, GA4 and HubSpot from the Payload admin
4810/wk0v3
analytics
Analytics Settings global for Google tags, custom scripts, pixels and UTM cookies on Next.js sites, with consent…
77627/wk0v4
payload plugin analytics
GA4-backed analytics dashboard in the Payload admin with a client-side tracking layer for Next.js front ends
70821/wk37v3
tracking
Tracking global and React providers for PostHog, Google Tag Manager and Vercel Analytics
6132/wk37v3
payload plugin google analytics
Google Analytics 4 dashboard widgets for the Payload admin panel
57621/wk8v3 v4
payload plugin ga4 ecommerce
GA4 reporting dashboards and per-record analytics tabs inside the Payload admin panel
44115/wk10v3