@power-seo/tracking 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,384 +1,405 @@
1
- # @power-seo/tracking — Analytics Script Builders & GDPR Consent Management for GA4, Clarity, PostHog, Plausible & Fathom
2
-
3
- [![npm version](https://img.shields.io/npm/v/@power-seo/tracking)](https://www.npmjs.com/package/@power-seo/tracking)
4
- [![npm downloads](https://img.shields.io/npm/dm/@power-seo/tracking)](https://www.npmjs.com/package/@power-seo/tracking)
5
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
- [![TypeScript](https://img.shields.io/badge/TypeScript-5.x-blue)](https://www.typescriptlang.org/)
7
- [![tree-shakeable](https://img.shields.io/badge/tree--shakeable-yes-brightgreen)](https://bundlephobia.com/package/@power-seo/tracking)
8
-
9
- ---
10
-
11
- ## Overview
12
-
13
- **@power-seo/tracking** is a consent-aware analytics toolkit for TypeScript that helps you manage GDPR-compliant script loading, define consent state, and query analytics APIs for GA4, Microsoft Clarity, PostHog, Plausible, and Fathom — all without runtime dependencies.
14
-
15
- **What it does**
16
- - ✅ **Script builders for 5 platforms** — `buildGA4Script`, `buildClarityScript`, `buildPostHogScript`, `buildPlausibleScript`, `buildFathomScript`
17
- - ✅ **Consent-aware loading** — every `ScriptConfig` exposes `shouldLoad(consentState)` to prevent loading without consent
18
- - ✅ **Consent manager** — `createConsentManager()` with `grant()`, `revoke()`, `grantAll()`, `revokeAll()`, `onChange()`
19
- - ✅ **React components** — `<AnalyticsScript>` and `<ConsentBanner>` for drop-in GDPR banner integration
20
- - ✅ **Analytics API clients** — query GA4, Clarity, PostHog, Plausible, and Fathom data programmatically
21
-
22
- **What it is not**
23
- - ❌ **Not a Tag Manager** — does not replace Google Tag Manager; it is a code-first alternative
24
- - ❌ **Not a legal compliance tool** — provides the technical mechanism; legal GDPR compliance requires proper privacy policy and DPA
25
-
26
- **Recommended for**
27
- - **Next.js App Router and Pages Router apps**, **Remix applications**, **SaaS products needing GDPR compliance**, and **analytics reporting dashboards**
28
-
29
- ---
30
-
31
- ## Why @power-seo/tracking Matters
32
-
33
- **The problem**
34
- - **Analytics scripts load before consent** — most analytics integrations don't check consent state before injecting `<script>` tags, violating GDPR
35
- - **5 different provider APIs** — each analytics platform has different initialization code, configuration, and loading strategy
36
- - **Consent state is UI state** — analytics loading needs to react to user consent choices in real time
37
-
38
- **Why developers care**
39
- - **Compliance:** GDPR requires analytics scripts not to load until the user grants consent
40
- - **Performance:** Consent-gated loading prevents unnecessary scripts from affecting LCP and TTI before user interaction
41
- - **UX:** A unified consent manager drives the consent banner, script loading, and API data fetching from one source of truth
42
-
43
- ---
44
-
45
- ## Key Features
46
-
47
- - **Script builders for 5 platforms** — GA4 (2 script tags), Microsoft Clarity, PostHog, Plausible, and Fathom Analytics
48
- - **Consent-aware loading** — every `ScriptConfig` exposes `shouldLoad(consentState)` — never loads a tracker without the right consent category
49
- - **Consent manager** — `createConsentManager()` returns a typed store with `grant()`, `revoke()`, `grantAll()`, `revokeAll()`, `getState()`, and `onChange()` subscription
50
- - **GDPR-friendly defaults** — `necessary` consent is always `true` and cannot be revoked; `analytics`, `marketing`, `preferences` default to `false`
51
- - **React components** — `<AnalyticsScript>` renders only consented scripts; `<ConsentBanner>` is a ready-to-use GDPR banner
52
- - **GA4 Data API client** — `createGA4Client()` queries reports, real-time data, and metadata
53
- - **Clarity API client** — `createClarityClient()` fetches projects, session insights, and heatmap data
54
- - **PostHog API client** — `createPostHogClient()` queries events, trends, funnels, and persons
55
- - **Plausible Stats API client** — `createPlausibleClient()` fetches timeseries, breakdowns, and aggregate stats
56
- - **Fathom API client** — `createFathomClient()` fetches sites, pageviews, and referrer data
57
- - **Zero runtime dependencies** — pure TypeScript with optional React peer dependency
58
- - **Full TypeScript support** — typed config interfaces, consent state, and response shapes for every provider
59
-
60
- ---
61
-
62
- ## Benefits of Using @power-seo/tracking
63
-
64
- - **GDPR compliance**: `shouldLoad(consent)` guarantees scripts only load when the correct consent category is granted
65
- - **Simpler integration**: One consent manager drives the consent banner UI, script loading, and API access — no fragmented state
66
- - **Better performance**: Analytics scripts with `lazyOnload` strategy don't block page render
67
- - **Faster delivery**: Typed script builders for 5 providers eliminate provider-specific documentation research
68
-
69
- ---
70
-
71
- ## Quick Start
72
-
73
- ```ts
74
- import { createConsentManager, buildGA4Script, buildPlausibleScript } from '@power-seo/tracking';
75
-
76
- // 1. Create consent manager — analytics off by default
77
- const consent = createConsentManager({
78
- necessary: true,
79
- analytics: false,
80
- marketing: false,
81
- preferences: false,
82
- });
83
-
84
- // 2. Build script configs
85
- const scripts = [
86
- ...buildGA4Script({ measurementId: 'G-XXXXXXX' }),
87
- buildPlausibleScript({ domain: 'example.com' }),
88
- ];
89
-
90
- // 3. Only load scripts where consent matches
91
- const toLoad = scripts.filter((s) => s.shouldLoad(consent.getState()));
92
- // toLoad [] until analytics consent is granted
93
-
94
- // 4. Grant consent (e.g. after user clicks "Accept All")
95
- consent.grantAll();
96
- const nowToLoad = scripts.filter((s) => s.shouldLoad(consent.getState()));
97
- // nowToLoad → [GA4Script1, GA4Script2, PlausibleScript]
98
- ```
99
-
100
- **What you should see**
101
- - Zero scripts loaded until `consent.grantAll()` is called
102
- - Scripts filtered by `shouldLoad(consentState)` — no analytics without user approval
103
-
104
- ---
105
-
106
- ## Installation
107
-
108
- ```bash
109
- npm i @power-seo/tracking
110
- # or
111
- yarn add @power-seo/tracking
112
- # or
113
- pnpm add @power-seo/tracking
114
- # or
115
- bun add @power-seo/tracking
116
- ```
117
-
118
- For React components, React 18+ is required as a peer dependency.
119
-
120
- ---
121
-
122
- ## Framework Compatibility
123
-
124
- **Supported**
125
- - ✅ Next.js App Router — use `<AnalyticsScript>` and `<ConsentBanner>` in root layout
126
- - ✅ Next.js Pages Router — use in `_app.tsx`
127
- - ✅ Remix — use in root route component
128
- - Node.js 18+ — API clients for server-side analytics data fetching
129
- - ✅ Vite + React — works in standard SPA setup
130
-
131
- **Environment notes**
132
- - **SSR/SSG:** Script builders and consent manager are SSR-safe; React components require client-side rendering for DOM injection
133
- - **Edge runtime:** Script builders and consent manager are edge-compatible; API clients require Node.js fetch
134
- - **Browser-only usage:** `shouldLoad()` and consent manager work in browser environments
135
-
136
- ---
137
-
138
- ## Use Cases
139
-
140
- - **GDPR-compliant web apps** load analytics scripts only after user consent
141
- - **SaaS marketing sites** track user behavior with GA4 while respecting privacy regulations
142
- - **E-commerce stores** Clarity session recordings for UX optimization with consent gate
143
- - **Multi-provider analytics** — run GA4 + Plausible + PostHog side-by-side for data validation
144
- - **Privacy-first apps** — Plausible or Fathom as cookieless, GDPR-compliant alternatives to GA4
145
- - **Analytics dashboards** — query GA4, Plausible, or Fathom APIs for custom reporting
146
- - **A/B testing pipelines** — PostHog feature flags + event tracking with consent management
147
- - **Enterprise compliance** — full audit trail of when consent was granted per category
148
-
149
- ---
150
-
151
- ## Example (Before / After)
152
-
153
- ```text
154
- Before:
155
- - GA4 script injected in <head> unconditionally violates GDPR before consent
156
- - 3 separate analytics integrations with different initialization patterns
157
- - Consent banner only hides scripts after first render → tracking still fires
158
-
159
- After (@power-seo/tracking):
160
- - buildGA4Script({ measurementId }) → ScriptConfig with shouldLoad(consent)
161
- - createConsentManager({ analytics: false }) → analytics = false until user clicks Accept
162
- - <AnalyticsScript scripts={scripts} consent={consent} /> → renders nothing until consented
163
- ```
164
-
165
- ---
166
-
167
- ## Implementation Best Practices
168
-
169
- - **Set `analytics: false` by default** in `createConsentManager()` GDPR requires opt-in, not opt-out
170
- - **Persist consent state** to `localStorage` or a cookie — re-read on page load to avoid showing the banner twice
171
- - **Use `onChange()`** to reactively reload scripts after consent is granted
172
- - **Do not load GA4 or Clarity** without `analytics` consent — these are tracking, not `necessary` scripts
173
- - **Include a working privacy policy link** in `<ConsentBanner privacyPolicyUrl="/privacy-policy" />`
174
-
175
- ---
176
-
177
- ## Architecture Overview
178
-
179
- **Where it runs**
180
- - **Build-time**: Script builder configs are defined server-side; passed to client as serialized props
181
- - **Runtime**: Consent manager runs client-side; `shouldLoad()` is evaluated on consent change
182
- - **CI/CD**: API clients run server-side for scheduled analytics data fetching and reporting
183
-
184
- **Data flow**
185
- 1. **Input**: Provider credentials (measurementId, projectId), initial consent state
186
- 2. **Analysis**: `shouldLoad(consentState)` evaluates per-script consent requirements
187
- 3. **Output**: Filtered `ScriptConfig[]` injected into `<head>` as `<script>` tags
188
- 4. **Action**: Analytics providers receive tracking data only when consent is granted
189
-
190
- ---
191
-
192
- ## Features Comparison with Popular Packages
193
-
194
- | Capability | @next/third-parties | partytown | cookiebot | @power-seo/tracking |
195
- |---|---:|---:|---:|---:|
196
- | Typed script builders | | ❌ | ❌ | ✅ |
197
- | Consent-aware `shouldLoad()` | | | ✅ | ✅ |
198
- | Built-in consent manager | | | (paid) | ✅ |
199
- | Analytics API clients | ❌ | ❌ | ❌ | ✅ |
200
- | 5-provider support | ⚠️ | ⚠️ | ✅ | ✅ |
201
- | Zero runtime dependencies | ✅ | ✅ | ❌ | ✅ |
202
-
203
- ---
204
-
205
- ## @power-seo Ecosystem
206
-
207
- All 17 packages are independently installable use only what you need.
208
-
209
- | Package | Install | Description |
210
- |---------|---------|-------------|
211
- | [`@power-seo/core`](https://www.npmjs.com/package/@power-seo/core) | `npm i @power-seo/core` | Framework-agnostic utilities, types, validators, and constants |
212
- | [`@power-seo/react`](https://www.npmjs.com/package/@power-seo/react) | `npm i @power-seo/react` | React SEO components — meta, Open Graph, Twitter Card, breadcrumbs |
213
- | [`@power-seo/meta`](https://www.npmjs.com/package/@power-seo/meta) | `npm i @power-seo/meta` | SSR meta helpers for Next.js App Router, Remix v2, and generic SSR |
214
- | [`@power-seo/schema`](https://www.npmjs.com/package/@power-seo/schema) | `npm i @power-seo/schema` | Type-safe JSON-LD structured data — 20 builders + 18 React components |
215
- | [`@power-seo/content-analysis`](https://www.npmjs.com/package/@power-seo/content-analysis) | `npm i @power-seo/content-analysis` | Yoast-style SEO content scoring engine with React components |
216
- | [`@power-seo/readability`](https://www.npmjs.com/package/@power-seo/readability) | `npm i @power-seo/readability` | Readability scoring — Flesch-Kincaid, Gunning Fog, Coleman-Liau, ARI |
217
- | [`@power-seo/preview`](https://www.npmjs.com/package/@power-seo/preview) | `npm i @power-seo/preview` | SERP, Open Graph, and Twitter/X Card preview generators |
218
- | [`@power-seo/sitemap`](https://www.npmjs.com/package/@power-seo/sitemap) | `npm i @power-seo/sitemap` | XML sitemap generation, streaming, index splitting, and validation |
219
- | [`@power-seo/redirects`](https://www.npmjs.com/package/@power-seo/redirects) | `npm i @power-seo/redirects` | Redirect engine with Next.js, Remix, and Express adapters |
220
- | [`@power-seo/links`](https://www.npmjs.com/package/@power-seo/links) | `npm i @power-seo/links` | Link graph analysis — orphan detection, suggestions, equity scoring |
221
- | [`@power-seo/audit`](https://www.npmjs.com/package/@power-seo/audit) | `npm i @power-seo/audit` | Full SEO audit engine — meta, content, structure, performance rules |
222
- | [`@power-seo/images`](https://www.npmjs.com/package/@power-seo/images) | `npm i @power-seo/images` | Image SEO — alt text, lazy loading, format analysis, image sitemaps |
223
- | [`@power-seo/ai`](https://www.npmjs.com/package/@power-seo/ai) | `npm i @power-seo/ai` | LLM-agnostic AI prompt templates and parsers for SEO tasks |
224
- | [`@power-seo/analytics`](https://www.npmjs.com/package/@power-seo/analytics) | `npm i @power-seo/analytics` | Merge GSC + audit data, trend analysis, ranking insights, dashboard |
225
- | [`@power-seo/search-console`](https://www.npmjs.com/package/@power-seo/search-console) | `npm i @power-seo/search-console` | Google Search Console API OAuth2, service account, URL inspection |
226
- | [`@power-seo/integrations`](https://www.npmjs.com/package/@power-seo/integrations) | `npm i @power-seo/integrations` | Semrush and Ahrefs API clients with rate limiting and pagination |
227
- | [`@power-seo/tracking`](https://www.npmjs.com/package/@power-seo/tracking) | `npm i @power-seo/tracking` | GA4, Clarity, PostHog, Plausible, Fathom scripts + consent management |
228
-
229
- ### Ecosystem vs alternatives
230
-
231
- | Need | Common approach | @power-seo approach |
232
- |---|---|---|
233
- | Analytics scripts | Direct `<script>` in HTML | `@power-seo/tracking` — consent-gated `ScriptConfig` |
234
- | GDPR consent banner | Cookiebot (paid) | `@power-seo/tracking` built-in `<ConsentBanner>` |
235
- | GSC data queries | `googleapis` | `@power-seo/search-console` — typed, auto-paginated |
236
- | SEO analytics dashboard | Looker Studio | `@power-seo/analytics` merge GSC + audit data |
237
-
238
- ---
239
-
240
- ## Enterprise Integration
241
-
242
- **Multi-tenant SaaS**
243
- - **Per-tenant analytics**: Each tenant supplies their own `measurementId`; instantiate separate `ScriptConfig` per tenant
244
- - **Consent per tenant**: Persist consent state in tenant-scoped cookies or DB; initialize `createConsentManager()` from stored state
245
- - **Data isolation**: API clients are instantiated per tenant no cross-tenant data leakage
246
-
247
- **ERP / internal portals**
248
- - Load Clarity session recordings only on public-facing pages, not authenticated internal routes
249
- - Use PostHog feature flags + event tracking for internal user behavior analytics with explicit consent
250
- - Build custom analytics reports with `createGA4Client()` or `createPlausibleClient()` for stakeholder dashboards
251
-
252
- **Recommended integration pattern**
253
- - Store consent state in **`localStorage`** or **HTTP-only cookie**
254
- - Initialize `createConsentManager()` from stored state on every page load
255
- - Trigger `onChange()` to reload scripts reactively when user updates consent preferences
256
- - Export consent events to **audit logs** for compliance documentation
257
-
258
- ---
259
-
260
- ## Scope and Limitations
261
-
262
- **This package does**
263
- - ✅ Build consent-aware script configs for 5 analytics platforms
264
- - Manage GDPR consent state with typed store and reactive subscriptions
265
- - ✅ Render consent-gated script tags and GDPR banner via React components
266
- - Query analytics data programmatically via 5 provider API clients
267
-
268
- **This package does not**
269
- - Replace a full consent management platform (CMP) for complex legal requirements
270
- - ❌ Implement consent record-keeping or proof-of-consent storage — handle this in your backend
271
- - ❌ Block server-side tracking (cookies set by CDN or server) — client-side only
272
-
273
- ---
274
-
275
- ## API Reference
276
-
277
- ### Script Builders
278
-
279
- | Function | Config Props | Returns | Description |
280
- |----------|-------------|---------|-------------|
281
- | `buildGA4Script` | `{ measurementId }` | `ScriptConfig[]` | Google Analytics 4 (2 script tags) |
282
- | `buildClarityScript` | `{ projectId }` | `ScriptConfig` | Microsoft Clarity |
283
- | `buildPostHogScript` | `{ apiKey, apiHost? }` | `ScriptConfig` | PostHog |
284
- | `buildPlausibleScript` | `{ domain, customDomain? }` | `ScriptConfig` | Plausible Analytics |
285
- | `buildFathomScript` | `{ siteId }` | `ScriptConfig` | Fathom Analytics |
286
-
287
- #### `ScriptConfig`
288
-
289
- | Prop | Type | Description |
290
- |------|------|-------------|
291
- | `src` | `string \| undefined` | External script URL |
292
- | `inlineScript` | `string \| undefined` | Inline JavaScript content |
293
- | `strategy` | `'beforeInteractive' \| 'afterInteractive' \| 'lazyOnload'` | Loading strategy hint |
294
- | `shouldLoad` | `(consent: ConsentState) => boolean` | Returns `true` if this script may load |
295
-
296
- ### Consent Manager
297
-
298
- ```ts
299
- function createConsentManager(initialState: Partial<ConsentState>): ConsentManager
300
- ```
301
-
302
- | Method | Signature | Description |
303
- |--------|-----------|-------------|
304
- | `grant` | `(category: ConsentCategory) => void` | Grant a consent category |
305
- | `revoke` | `(category: ConsentCategory) => void` | Revoke a consent category |
306
- | `grantAll` | `() => void` | Grant all non-necessary categories |
307
- | `revokeAll` | `() => void` | Revoke all non-necessary categories |
308
- | `getState` | `() => ConsentState` | Get the current consent snapshot |
309
- | `onChange` | `(cb: ConsentChangeCallback) => () => void` | Subscribe to changes; returns unsubscribe |
310
-
311
- ### API Clients
312
-
313
- ```ts
314
- function createGA4Client(config: GA4Config): GA4Client
315
- function createClarityClient(config: ClarityConfig): ClarityClient
316
- function createPostHogClient(config: PostHogConfig): PostHogClient
317
- function createPlausibleClient(config: PlausibleConfig): PlausibleClient
318
- function createFathomClient(config: FathomConfig): FathomClient
319
- ```
320
-
321
- ### React Components
322
-
323
- | Component | Props | Description |
324
- |-----------|-------|-------------|
325
- | `<AnalyticsScript>` | `{ scripts: ScriptConfig[], consent: ConsentState }` | Renders `<script>` tags that pass `shouldLoad(consent)` |
326
- | `<ConsentBanner>` | `{ manager: ConsentManager, privacyPolicyUrl?: string }` | GDPR cookie consent banner with Accept All / Reject All |
327
-
328
- ### Types
329
-
330
- ```ts
331
- import type {
332
- ConsentCategory, // 'necessary' | 'analytics' | 'marketing' | 'preferences'
333
- ConsentState, // { necessary, analytics, marketing, preferences }
334
- ConsentManager,
335
- ScriptConfig,
336
- GA4Config, GA4Client,
337
- ClarityConfig, ClarityClient,
338
- PostHogConfig, PostHogClient,
339
- PlausibleConfig, PlausibleClient,
340
- FathomConfig, FathomClient,
341
- } from '@power-seo/tracking';
342
- ```
343
-
344
- ---
345
-
346
- ## Contributing
347
-
348
- - Issues: [github.com/cybercraftbd/power-seo/issues](https://github.com/cybercraftbd/power-seo/issues)
349
- - PRs: [github.com/cybercraftbd/power-seo/pulls](https://github.com/cybercraftbd/power-seo/pulls)
350
- - Development setup:
351
- 1. `pnpm i`
352
- 2. `pnpm build`
353
- 3. `pnpm test`
354
-
355
- **Release workflow**
356
- - `npm version patch|minor|major`
357
- - `npm publish --access public`
358
-
359
- ---
360
-
361
- ## About CyberCraft Bangladesh
362
-
363
- **CyberCraft Bangladesh** is a Bangladesh-based enterprise-grade software engineering company specializing in ERP system development, AI-powered SaaS and business applications, full-stack SEO services, custom website development, and scalable eCommerce platforms. We design and develop intelligent, automation-driven SaaS and enterprise solutions that help startups, SMEs, NGOs, educational institutes, and large organizations streamline operations, enhance digital visibility, and accelerate growth through modern cloud-native technologies.
364
-
365
- | | |
366
- |---|---|
367
- | **Website** | [ccbd.dev](https://ccbd.dev) |
368
- | **GitHub** | [github.com/cybercraftbd](https://github.com/cybercraftbd) |
369
- | **npm Organization** | [npmjs.com/org/power-seo](https://www.npmjs.com/org/power-seo) |
370
- | **Email** | [info@ccbd.dev](mailto:info@ccbd.dev) |
371
-
372
- ---
373
-
374
- ## License
375
-
376
- **MIT**
377
-
378
- ---
379
-
380
- ## Keywords
381
-
382
- ```text
383
- analytics, ga4, google-analytics, microsoft-clarity, posthog, plausible, fathom, gdpr, consent-management, cookie-consent, typescript, react, nextjs, privacy
384
- ```
1
+ # @power-seo/tracking — Analytics Script Builders & GDPR Consent Management for GA4, Clarity, PostHog, Plausible & Fathom
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@power-seo/tracking)](https://www.npmjs.com/package/@power-seo/tracking)
4
+ [![npm downloads](https://img.shields.io/npm/dm/@power-seo/tracking)](https://www.npmjs.com/package/@power-seo/tracking)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.x-blue)](https://www.typescriptlang.org/)
7
+ [![tree-shakeable](https://img.shields.io/badge/tree--shakeable-yes-brightgreen)](https://bundlephobia.com/package/@power-seo/tracking)
8
+
9
+ ---
10
+
11
+ ## Overview
12
+
13
+ **@power-seo/tracking** is a consent-aware analytics toolkit for TypeScript that helps you manage GDPR-compliant script loading, define consent state, and query analytics APIs for GA4, Microsoft Clarity, PostHog, Plausible, and Fathom — all without runtime dependencies.
14
+
15
+ **What it does**
16
+
17
+ - ✅ **Script builders for 5 platforms** — `buildGA4Script`, `buildClarityScript`, `buildPostHogScript`, `buildPlausibleScript`, `buildFathomScript`
18
+ - ✅ **Consent-aware loading** — every `ScriptConfig` exposes `shouldLoad(consentState)` to prevent loading without consent
19
+ - ✅ **Consent manager** — `createConsentManager()` with `grant()`, `revoke()`, `grantAll()`, `revokeAll()`, `onChange()`
20
+ - ✅ **React components** — `<AnalyticsScript>` and `<ConsentBanner>` for drop-in GDPR banner integration
21
+ - ✅ **Analytics API clients** — query GA4, Clarity, PostHog, Plausible, and Fathom data programmatically
22
+
23
+ **What it is not**
24
+
25
+ - ❌ **Not a Tag Manager** — does not replace Google Tag Manager; it is a code-first alternative
26
+ - ❌ **Not a legal compliance tool** — provides the technical mechanism; legal GDPR compliance requires proper privacy policy and DPA
27
+
28
+ **Recommended for**
29
+
30
+ - **Next.js App Router and Pages Router apps**, **Remix applications**, **SaaS products needing GDPR compliance**, and **analytics reporting dashboards**
31
+
32
+ ---
33
+
34
+ ## Why @power-seo/tracking Matters
35
+
36
+ **The problem**
37
+
38
+ - **Analytics scripts load before consent** — most analytics integrations don't check consent state before injecting `<script>` tags, violating GDPR
39
+ - **5 different provider APIs** — each analytics platform has different initialization code, configuration, and loading strategy
40
+ - **Consent state is UI state** analytics loading needs to react to user consent choices in real time
41
+
42
+ **Why developers care**
43
+
44
+ - **Compliance:** GDPR requires analytics scripts not to load until the user grants consent
45
+ - **Performance:** Consent-gated loading prevents unnecessary scripts from affecting LCP and TTI before user interaction
46
+ - **UX:** A unified consent manager drives the consent banner, script loading, and API data fetching from one source of truth
47
+
48
+ ---
49
+
50
+ ## Key Features
51
+
52
+ - **Script builders for 5 platforms** — GA4 (2 script tags), Microsoft Clarity, PostHog, Plausible, and Fathom Analytics
53
+ - **Consent-aware loading** — every `ScriptConfig` exposes `shouldLoad(consentState)` never loads a tracker without the right consent category
54
+ - **Consent manager** — `createConsentManager()` returns a typed store with `grant()`, `revoke()`, `grantAll()`, `revokeAll()`, `getState()`, and `onChange()` subscription
55
+ - **GDPR-friendly defaults** — `necessary` consent is always `true` and cannot be revoked; `analytics`, `marketing`, `preferences` default to `false`
56
+ - **React components** — `<AnalyticsScript>` renders only consented scripts; `<ConsentBanner>` is a ready-to-use GDPR banner
57
+ - **GA4 Data API client** — `createGA4Client()` queries reports, real-time data, and metadata
58
+ - **Clarity API client** — `createClarityClient()` fetches projects, session insights, and heatmap data
59
+ - **PostHog API client** — `createPostHogClient()` queries events, trends, funnels, and persons
60
+ - **Plausible Stats API client** — `createPlausibleClient()` fetches timeseries, breakdowns, and aggregate stats
61
+ - **Fathom API client** — `createFathomClient()` fetches sites, pageviews, and referrer data
62
+ - **Zero runtime dependencies** — pure TypeScript with optional React peer dependency
63
+ - **Full TypeScript support** — typed config interfaces, consent state, and response shapes for every provider
64
+
65
+ ---
66
+
67
+ ## Benefits of Using @power-seo/tracking
68
+
69
+ - **GDPR compliance**: `shouldLoad(consent)` guarantees scripts only load when the correct consent category is granted
70
+ - **Simpler integration**: One consent manager drives the consent banner UI, script loading, and API access — no fragmented state
71
+ - **Better performance**: Analytics scripts with `lazyOnload` strategy don't block page render
72
+ - **Faster delivery**: Typed script builders for 5 providers eliminate provider-specific documentation research
73
+
74
+ ---
75
+
76
+ ## Quick Start
77
+
78
+ ```ts
79
+ import { createConsentManager, buildGA4Script, buildPlausibleScript } from '@power-seo/tracking';
80
+
81
+ // 1. Create consent manager — analytics off by default
82
+ const consent = createConsentManager({
83
+ necessary: true,
84
+ analytics: false,
85
+ marketing: false,
86
+ preferences: false,
87
+ });
88
+
89
+ // 2. Build script configs
90
+ const scripts = [
91
+ ...buildGA4Script({ measurementId: 'G-XXXXXXX' }),
92
+ buildPlausibleScript({ domain: 'example.com' }),
93
+ ];
94
+
95
+ // 3. Only load scripts where consent matches
96
+ const toLoad = scripts.filter((s) => s.shouldLoad(consent.getState()));
97
+ // toLoad → [] until analytics consent is granted
98
+
99
+ // 4. Grant consent (e.g. after user clicks "Accept All")
100
+ consent.grantAll();
101
+ const nowToLoad = scripts.filter((s) => s.shouldLoad(consent.getState()));
102
+ // nowToLoad [GA4Script1, GA4Script2, PlausibleScript]
103
+ ```
104
+
105
+ **What you should see**
106
+
107
+ - Zero scripts loaded until `consent.grantAll()` is called
108
+ - Scripts filtered by `shouldLoad(consentState)` — no analytics without user approval
109
+
110
+ ---
111
+
112
+ ## Installation
113
+
114
+ ```bash
115
+ npm i @power-seo/tracking
116
+ # or
117
+ yarn add @power-seo/tracking
118
+ # or
119
+ pnpm add @power-seo/tracking
120
+ # or
121
+ bun add @power-seo/tracking
122
+ ```
123
+
124
+ For React components, React 18+ is required as a peer dependency.
125
+
126
+ ---
127
+
128
+ ## Framework Compatibility
129
+
130
+ **Supported**
131
+
132
+ - Next.js App Router use `<AnalyticsScript>` and `<ConsentBanner>` in root layout
133
+ - Next.js Pages Router use in `_app.tsx`
134
+ - Remix use in root route component
135
+ - ✅ Node.js 18+ — API clients for server-side analytics data fetching
136
+ - ✅ Vite + React — works in standard SPA setup
137
+
138
+ **Environment notes**
139
+
140
+ - **SSR/SSG:** Script builders and consent manager are SSR-safe; React components require client-side rendering for DOM injection
141
+ - **Edge runtime:** Script builders and consent manager are edge-compatible; API clients require Node.js fetch
142
+ - **Browser-only usage:** `shouldLoad()` and consent manager work in browser environments
143
+
144
+ ---
145
+
146
+ ## Use Cases
147
+
148
+ - **GDPR-compliant web apps** — load analytics scripts only after user consent
149
+ - **SaaS marketing sites** — track user behavior with GA4 while respecting privacy regulations
150
+ - **E-commerce stores** — Clarity session recordings for UX optimization with consent gate
151
+ - **Multi-provider analytics** run GA4 + Plausible + PostHog side-by-side for data validation
152
+ - **Privacy-first apps** — Plausible or Fathom as cookieless, GDPR-compliant alternatives to GA4
153
+ - **Analytics dashboards** — query GA4, Plausible, or Fathom APIs for custom reporting
154
+ - **A/B testing pipelines** — PostHog feature flags + event tracking with consent management
155
+ - **Enterprise compliance** full audit trail of when consent was granted per category
156
+
157
+ ---
158
+
159
+ ## Example (Before / After)
160
+
161
+ ```text
162
+ Before:
163
+ - GA4 script injected in <head> unconditionally → violates GDPR before consent
164
+ - 3 separate analytics integrations with different initialization patterns
165
+ - Consent banner only hides scripts after first render → tracking still fires
166
+
167
+ After (@power-seo/tracking):
168
+ - buildGA4Script({ measurementId }) → ScriptConfig with shouldLoad(consent)
169
+ - createConsentManager({ analytics: false }) analytics = false until user clicks Accept
170
+ - <AnalyticsScript scripts={scripts} consent={consent} /> renders nothing until consented
171
+ ```
172
+
173
+ ---
174
+
175
+ ## Implementation Best Practices
176
+
177
+ - **Set `analytics: false` by default** in `createConsentManager()` — GDPR requires opt-in, not opt-out
178
+ - **Persist consent state** to `localStorage` or a cookie — re-read on page load to avoid showing the banner twice
179
+ - **Use `onChange()`** to reactively reload scripts after consent is granted
180
+ - **Do not load GA4 or Clarity** without `analytics` consent these are tracking, not `necessary` scripts
181
+ - **Include a working privacy policy link** in `<ConsentBanner privacyPolicyUrl="/privacy-policy" />`
182
+
183
+ ---
184
+
185
+ ## Architecture Overview
186
+
187
+ **Where it runs**
188
+
189
+ - **Build-time**: Script builder configs are defined server-side; passed to client as serialized props
190
+ - **Runtime**: Consent manager runs client-side; `shouldLoad()` is evaluated on consent change
191
+ - **CI/CD**: API clients run server-side for scheduled analytics data fetching and reporting
192
+
193
+ **Data flow**
194
+
195
+ 1. **Input**: Provider credentials (measurementId, projectId), initial consent state
196
+ 2. **Analysis**: `shouldLoad(consentState)` evaluates per-script consent requirements
197
+ 3. **Output**: Filtered `ScriptConfig[]` injected into `<head>` as `<script>` tags
198
+ 4. **Action**: Analytics providers receive tracking data only when consent is granted
199
+
200
+ ---
201
+
202
+ ## Features Comparison with Popular Packages
203
+
204
+ | Capability | @next/third-parties | partytown | cookiebot | @power-seo/tracking |
205
+ | ---------------------------- | ------------------: | --------: | --------: | ------------------: |
206
+ | Typed script builders | ❌ | ❌ | ❌ | ✅ |
207
+ | Consent-aware `shouldLoad()` | ❌ | ❌ | ✅ | ✅ |
208
+ | Built-in consent manager | ❌ | ❌ | ✅ (paid) | ✅ |
209
+ | Analytics API clients | | ❌ | | ✅ |
210
+ | 5-provider support | ⚠️ | ⚠️ | ✅ | ✅ |
211
+ | Zero runtime dependencies | | ✅ | ❌ | |
212
+
213
+ ---
214
+
215
+ ## @power-seo Ecosystem
216
+
217
+ All 17 packages are independently installable use only what you need.
218
+
219
+ | Package | Install | Description |
220
+ | ------------------------------------------------------------------------------------------ | ----------------------------------- | ----------------------------------------------------------------------- |
221
+ | [`@power-seo/core`](https://www.npmjs.com/package/@power-seo/core) | `npm i @power-seo/core` | Framework-agnostic utilities, types, validators, and constants |
222
+ | [`@power-seo/react`](https://www.npmjs.com/package/@power-seo/react) | `npm i @power-seo/react` | React SEO components meta, Open Graph, Twitter Card, breadcrumbs |
223
+ | [`@power-seo/meta`](https://www.npmjs.com/package/@power-seo/meta) | `npm i @power-seo/meta` | SSR meta helpers for Next.js App Router, Remix v2, and generic SSR |
224
+ | [`@power-seo/schema`](https://www.npmjs.com/package/@power-seo/schema) | `npm i @power-seo/schema` | Type-safe JSON-LD structured data 20 builders + 18 React components |
225
+ | [`@power-seo/content-analysis`](https://www.npmjs.com/package/@power-seo/content-analysis) | `npm i @power-seo/content-analysis` | Yoast-style SEO content scoring engine with React components |
226
+ | [`@power-seo/readability`](https://www.npmjs.com/package/@power-seo/readability) | `npm i @power-seo/readability` | Readability scoring Flesch-Kincaid, Gunning Fog, Coleman-Liau, ARI |
227
+ | [`@power-seo/preview`](https://www.npmjs.com/package/@power-seo/preview) | `npm i @power-seo/preview` | SERP, Open Graph, and Twitter/X Card preview generators |
228
+ | [`@power-seo/sitemap`](https://www.npmjs.com/package/@power-seo/sitemap) | `npm i @power-seo/sitemap` | XML sitemap generation, streaming, index splitting, and validation |
229
+ | [`@power-seo/redirects`](https://www.npmjs.com/package/@power-seo/redirects) | `npm i @power-seo/redirects` | Redirect engine with Next.js, Remix, and Express adapters |
230
+ | [`@power-seo/links`](https://www.npmjs.com/package/@power-seo/links) | `npm i @power-seo/links` | Link graph analysis — orphan detection, suggestions, equity scoring |
231
+ | [`@power-seo/audit`](https://www.npmjs.com/package/@power-seo/audit) | `npm i @power-seo/audit` | Full SEO audit engine — meta, content, structure, performance rules |
232
+ | [`@power-seo/images`](https://www.npmjs.com/package/@power-seo/images) | `npm i @power-seo/images` | Image SEO — alt text, lazy loading, format analysis, image sitemaps |
233
+ | [`@power-seo/ai`](https://www.npmjs.com/package/@power-seo/ai) | `npm i @power-seo/ai` | LLM-agnostic AI prompt templates and parsers for SEO tasks |
234
+ | [`@power-seo/analytics`](https://www.npmjs.com/package/@power-seo/analytics) | `npm i @power-seo/analytics` | Merge GSC + audit data, trend analysis, ranking insights, dashboard |
235
+ | [`@power-seo/search-console`](https://www.npmjs.com/package/@power-seo/search-console) | `npm i @power-seo/search-console` | Google Search Console API OAuth2, service account, URL inspection |
236
+ | [`@power-seo/integrations`](https://www.npmjs.com/package/@power-seo/integrations) | `npm i @power-seo/integrations` | Semrush and Ahrefs API clients with rate limiting and pagination |
237
+ | [`@power-seo/tracking`](https://www.npmjs.com/package/@power-seo/tracking) | `npm i @power-seo/tracking` | GA4, Clarity, PostHog, Plausible, Fathom — scripts + consent management |
238
+
239
+ ### Ecosystem vs alternatives
240
+
241
+ | Need | Common approach | @power-seo approach |
242
+ | ----------------------- | ------------------------- | ---------------------------------------------------- |
243
+ | Analytics scripts | Direct `<script>` in HTML | `@power-seo/tracking` consent-gated `ScriptConfig` |
244
+ | GDPR consent banner | Cookiebot (paid) | `@power-seo/tracking` built-in `<ConsentBanner>` |
245
+ | GSC data queries | `googleapis` | `@power-seo/search-console`typed, auto-paginated |
246
+ | SEO analytics dashboard | Looker Studio | `@power-seo/analytics` — merge GSC + audit data |
247
+
248
+ ---
249
+
250
+ ## Enterprise Integration
251
+
252
+ **Multi-tenant SaaS**
253
+
254
+ - **Per-tenant analytics**: Each tenant supplies their own `measurementId`; instantiate separate `ScriptConfig` per tenant
255
+ - **Consent per tenant**: Persist consent state in tenant-scoped cookies or DB; initialize `createConsentManager()` from stored state
256
+ - **Data isolation**: API clients are instantiated per tenant — no cross-tenant data leakage
257
+
258
+ **ERP / internal portals**
259
+
260
+ - Load Clarity session recordings only on public-facing pages, not authenticated internal routes
261
+ - Use PostHog feature flags + event tracking for internal user behavior analytics with explicit consent
262
+ - Build custom analytics reports with `createGA4Client()` or `createPlausibleClient()` for stakeholder dashboards
263
+
264
+ **Recommended integration pattern**
265
+
266
+ - Store consent state in **`localStorage`** or **HTTP-only cookie**
267
+ - Initialize `createConsentManager()` from stored state on every page load
268
+ - Trigger `onChange()` to reload scripts reactively when user updates consent preferences
269
+ - Export consent events to **audit logs** for compliance documentation
270
+
271
+ ---
272
+
273
+ ## Scope and Limitations
274
+
275
+ **This package does**
276
+
277
+ - Build consent-aware script configs for 5 analytics platforms
278
+ - ✅ Manage GDPR consent state with typed store and reactive subscriptions
279
+ - Render consent-gated script tags and GDPR banner via React components
280
+ - ✅ Query analytics data programmatically via 5 provider API clients
281
+
282
+ **This package does not**
283
+
284
+ - Replace a full consent management platform (CMP) for complex legal requirements
285
+ - Implement consent record-keeping or proof-of-consent storage handle this in your backend
286
+ - ❌ Block server-side tracking (cookies set by CDN or server) — client-side only
287
+
288
+ ---
289
+
290
+ ## API Reference
291
+
292
+ ### Script Builders
293
+
294
+ | Function | Config Props | Returns | Description |
295
+ | ---------------------- | --------------------------- | ---------------- | ---------------------------------- |
296
+ | `buildGA4Script` | `{ measurementId }` | `ScriptConfig[]` | Google Analytics 4 (2 script tags) |
297
+ | `buildClarityScript` | `{ projectId }` | `ScriptConfig` | Microsoft Clarity |
298
+ | `buildPostHogScript` | `{ apiKey, apiHost? }` | `ScriptConfig` | PostHog |
299
+ | `buildPlausibleScript` | `{ domain, customDomain? }` | `ScriptConfig` | Plausible Analytics |
300
+ | `buildFathomScript` | `{ siteId }` | `ScriptConfig` | Fathom Analytics |
301
+
302
+ #### `ScriptConfig`
303
+
304
+ | Prop | Type | Description |
305
+ | -------------- | ----------------------------------------------------------- | -------------------------------------- |
306
+ | `src` | `string \| undefined` | External script URL |
307
+ | `inlineScript` | `string \| undefined` | Inline JavaScript content |
308
+ | `strategy` | `'beforeInteractive' \| 'afterInteractive' \| 'lazyOnload'` | Loading strategy hint |
309
+ | `shouldLoad` | `(consent: ConsentState) => boolean` | Returns `true` if this script may load |
310
+
311
+ ### Consent Manager
312
+
313
+ ```ts
314
+ function createConsentManager(initialState: Partial<ConsentState>): ConsentManager;
315
+ ```
316
+
317
+ | Method | Signature | Description |
318
+ | ----------- | ------------------------------------------- | ----------------------------------------- |
319
+ | `grant` | `(category: ConsentCategory) => void` | Grant a consent category |
320
+ | `revoke` | `(category: ConsentCategory) => void` | Revoke a consent category |
321
+ | `grantAll` | `() => void` | Grant all non-necessary categories |
322
+ | `revokeAll` | `() => void` | Revoke all non-necessary categories |
323
+ | `getState` | `() => ConsentState` | Get the current consent snapshot |
324
+ | `onChange` | `(cb: ConsentChangeCallback) => () => void` | Subscribe to changes; returns unsubscribe |
325
+
326
+ ### API Clients
327
+
328
+ ```ts
329
+ function createGA4Client(config: GA4Config): GA4Client;
330
+ function createClarityClient(config: ClarityConfig): ClarityClient;
331
+ function createPostHogClient(config: PostHogConfig): PostHogClient;
332
+ function createPlausibleClient(config: PlausibleConfig): PlausibleClient;
333
+ function createFathomClient(config: FathomConfig): FathomClient;
334
+ ```
335
+
336
+ ### React Components
337
+
338
+ | Component | Props | Description |
339
+ | ------------------- | -------------------------------------------------------- | ------------------------------------------------------- |
340
+ | `<AnalyticsScript>` | `{ scripts: ScriptConfig[], consent: ConsentState }` | Renders `<script>` tags that pass `shouldLoad(consent)` |
341
+ | `<ConsentBanner>` | `{ manager: ConsentManager, privacyPolicyUrl?: string }` | GDPR cookie consent banner with Accept All / Reject All |
342
+
343
+ ### Types
344
+
345
+ ```ts
346
+ import type {
347
+ ConsentCategory, // 'necessary' | 'analytics' | 'marketing' | 'preferences'
348
+ ConsentState, // { necessary, analytics, marketing, preferences }
349
+ ConsentManager,
350
+ ScriptConfig,
351
+ GA4Config,
352
+ GA4Client,
353
+ ClarityConfig,
354
+ ClarityClient,
355
+ PostHogConfig,
356
+ PostHogClient,
357
+ PlausibleConfig,
358
+ PlausibleClient,
359
+ FathomConfig,
360
+ FathomClient,
361
+ } from '@power-seo/tracking';
362
+ ```
363
+
364
+ ---
365
+
366
+ ## Contributing
367
+
368
+ - Issues: [github.com/cybercraftbd/power-seo/issues](https://github.com/cybercraftbd/power-seo/issues)
369
+ - PRs: [github.com/cybercraftbd/power-seo/pulls](https://github.com/cybercraftbd/power-seo/pulls)
370
+ - Development setup:
371
+ 1. `pnpm i`
372
+ 2. `pnpm build`
373
+ 3. `pnpm test`
374
+
375
+ **Release workflow**
376
+
377
+ - `npm version patch|minor|major`
378
+ - `npm publish --access public`
379
+
380
+ ---
381
+
382
+ ## About CyberCraft Bangladesh
383
+
384
+ **CyberCraft Bangladesh** is a Bangladesh-based enterprise-grade software engineering company specializing in ERP system development, AI-powered SaaS and business applications, full-stack SEO services, custom website development, and scalable eCommerce platforms. We design and develop intelligent, automation-driven SaaS and enterprise solutions that help startups, SMEs, NGOs, educational institutes, and large organizations streamline operations, enhance digital visibility, and accelerate growth through modern cloud-native technologies.
385
+
386
+ | | |
387
+ | -------------------- | -------------------------------------------------------------- |
388
+ | **Website** | [ccbd.dev](https://ccbd.dev) |
389
+ | **GitHub** | [github.com/cybercraftbd](https://github.com/cybercraftbd) |
390
+ | **npm Organization** | [npmjs.com/org/power-seo](https://www.npmjs.com/org/power-seo) |
391
+ | **Email** | [info@ccbd.dev](mailto:info@ccbd.dev) |
392
+
393
+ ---
394
+
395
+ ## License
396
+
397
+ **MIT**
398
+
399
+ ---
400
+
401
+ ## Keywords
402
+
403
+ ```text
404
+ analytics, ga4, google-analytics, microsoft-clarity, posthog, plausible, fathom, gdpr, consent-management, cookie-consent, typescript, react, nextjs, privacy
405
+ ```