🚨 Active Supply Chain Attack:node-ipc Package Compromised.Learn More
Socket
Book a DemoSign in
Socket

@power-seo/tracking

Package Overview
Dependencies
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@power-seo/tracking

Analytics platform integration with script builders, consent management, and React components

latest
Source
npmnpm
Version
1.0.15
Version published
Maintainers
1
Created
Source

@power-seo/tracking

tracking banner

Consent-aware analytics script builders and GDPR consent management for TypeScript — GA4, Microsoft Clarity, PostHog, Plausible, and Fathom with a unified shouldLoad(consentState) API and React components.

npm version npm downloads Socket License: MIT TypeScript tree-shakeable

@power-seo/tracking is a consent-aware analytics toolkit for TypeScript. Build typed script configs for five analytics platforms, manage GDPR consent state with a reactive store, and render consent-gated script tags and a cookie banner via drop-in React components. Every ScriptConfig exposes shouldLoad(consentState) — scripts never load without the correct consent category. The consent manager defaults to necessary: true and all other categories to false, satisfying GDPR opt-in requirements out of the box. Five typed API clients let you query GA4, Clarity, PostHog, Plausible, and Fathom data server-side for custom reporting and dashboards.

Zero runtime dependencies — pure TypeScript with an optional React 18+ peer dependency for the <AnalyticsScript> and <ConsentBanner> components.

Why @power-seo/tracking?

WithoutWith
GDPR consent❌ Scripts load unconditionally in <head>shouldLoad(consentState) gates every script
Consent manager❌ Custom UI state per projectcreateConsentManager() with typed categories
Multi-provider❌ Different init code per analytics platform✅ One API for GA4, Clarity, PostHog, Plausible, Fathom
React integration❌ Manual <script> injection in layout<AnalyticsScript> and <ConsentBanner> drop-in
API data access❌ Platform-specific SDK research per provider✅ Typed clients for all 5 providers
Performance❌ Scripts block LCP before user interaction✅ Lazy loading strategy prevents render blocking
TypeScript❌ Loose config objects with no type checking✅ Typed ScriptConfig, ConsentState, ConsentManager

Tracking Comparison

Features

  • Script builders for 5 platformsbuildGA4Script (2 script tags), buildClarityScript, buildPostHogScript, buildPlausibleScript, buildFathomScript
  • Consent-aware loading — every ScriptConfig exposes shouldLoad(consentState) — scripts never load without the right consent category
  • Consent managercreateConsentManager() returns a typed store with grant(), revoke(), grantAll(), revokeAll(), getState(), and onChange() subscription
  • GDPR-friendly defaultsnecessary consent is always true and cannot be revoked; analytics, marketing, preferences default to false
  • React components<AnalyticsScript> renders only consented scripts; <ConsentBanner> is a ready-to-use GDPR cookie banner
  • GA4 Data API clientcreateGA4Client() queries reports, real-time data, and metadata
  • Clarity API clientcreateClarityClient() fetches projects, session insights, and heatmap data
  • PostHog API clientcreatePostHogClient() queries events, trends, funnels, and persons
  • Plausible Stats API clientcreatePlausibleClient() fetches timeseries, breakdowns, and aggregate stats
  • Fathom API clientcreateFathomClient() fetches sites, pageviews, and referrer data
  • Framework-agnostic — script builders and consent manager work in Next.js, Remix, Vite, Vanilla JS, and Edge runtimes
  • Full TypeScript support — typed config interfaces, consent state, and response shapes for every provider
  • Tree-shakeable — import only the providers you use; zero dead code in your bundle

Consent Banner UI

Comparison

Feature@next/third-partiespartytowncookiebot@power-seo/tracking
Typed script builders
Consent-aware shouldLoad()
Built-in consent manager✅ (paid)
Analytics API clients
5-provider support⚠️⚠️
Zero runtime dependencies
TypeScript-first
React components⚠️

Conditional Loading Accuracy

Installation

npm install @power-seo/tracking
yarn add @power-seo/tracking
pnpm add @power-seo/tracking

For React components, React 18+ is required as a peer dependency.

Quick Start

import { createConsentManager, buildGA4Script, buildPlausibleScript } from '@power-seo/tracking';

// 1. Create consent manager — analytics off by default (GDPR opt-in)
const consent = createConsentManager({
  necessary: true,
  analytics: false,
  marketing: false,
  preferences: false,
});

// 2. Build script configs for your providers
const scripts = [
  ...buildGA4Script({ measurementId: 'G-XXXXXXX' }),
  buildPlausibleScript({ domain: 'example.com' }),
];

// 3. Only load scripts where consent matches
const toLoad = scripts.filter((s) => s.shouldLoad(consent.getState()));
// toLoad → [] until analytics consent is granted

// 4. Grant consent (e.g. after user clicks "Accept All")
consent.grantAll();
const nowToLoad = scripts.filter((s) => s.shouldLoad(consent.getState()));
// nowToLoad → [GA4Script1, GA4Script2, PlausibleScript]

Consent Benefit

Usage

Script Builders

import {
  buildGA4Script,
  buildClarityScript,
  buildPostHogScript,
  buildPlausibleScript,
  buildFathomScript,
} from '@power-seo/tracking';

const scripts = [
  ...buildGA4Script({ measurementId: 'G-XXXXXXX' }), // returns ScriptConfig[]
  buildClarityScript({ projectId: 'abc123' }),
  buildPostHogScript({ apiKey: 'phc_xxx', apiHost: 'https://app.posthog.com' }),
  buildPlausibleScript({ domain: 'example.com' }),
  buildFathomScript({ siteId: 'ABCDEFGH' }),
];
import { createConsentManager } from '@power-seo/tracking';

const consent = createConsentManager({ necessary: true, analytics: false });

// Grant/revoke individual categories
consent.grant('analytics');
consent.revoke('marketing');

// Grant or revoke all non-necessary categories
consent.grantAll();
consent.revokeAll();

// Read current state
const state = consent.getState();
// { necessary: true, analytics: true, marketing: false, preferences: false }

// Subscribe to changes — returns unsubscribe function
const unsubscribe = consent.onChange((newState) => {
  console.log('Consent changed:', newState);
});

React — AnalyticsScript

'use client';

import { AnalyticsScript } from '@power-seo/tracking/react';
import { buildGA4Script, createConsentManager } from '@power-seo/tracking';

const consent = createConsentManager({ necessary: true, analytics: false });
const scripts = buildGA4Script({ measurementId: 'G-XXXXXXX' });

export default function Layout({ children }: { children: React.ReactNode }) {
  return (
    <html>
      <head>
        <AnalyticsScript scripts={scripts} consent={consent.getState()} />
      </head>
      <body>{children}</body>
    </html>
  );
}

React — ConsentBanner

'use client';

import { ConsentBanner } from '@power-seo/tracking/react';
import { createConsentManager } from '@power-seo/tracking';

const consent = createConsentManager({ necessary: true, analytics: false });

export function CookieBanner() {
  return <ConsentBanner manager={consent} privacyPolicyUrl="/privacy-policy" />;
}

Analytics API Clients

import { createGA4Client, createPlausibleClient } from '@power-seo/tracking';

// Query GA4 reports
const ga4 = createGA4Client(process.env.GA4_ACCESS_TOKEN!);

// Query Plausible stats
const plausible = createPlausibleClient(process.env.PLAUSIBLE_API_KEY!);

const stats = await plausible.getAggregate('your-site-id', '7d');
console.log(stats.visitors, stats.pageviews);
'use client';

import { useEffect, useState } from 'react';
import { createConsentManager, buildGA4Script } from '@power-seo/tracking';

const consent = createConsentManager({ necessary: true, analytics: false });
const scripts = buildGA4Script({ measurementId: 'G-XXXXXXX' });

export function AnalyticsLoader() {
  const [state, setState] = useState(consent.getState());

  useEffect(() => {
    return consent.onChange(setState);
  }, []);

  const toLoad = scripts.filter((s) => s.shouldLoad(state));
  // inject toLoad scripts into document.head
  return null;
}

API Reference

Script Builders

FunctionConfig PropsReturnsDescription
buildGA4Script{ measurementId }ScriptConfig[]Google Analytics 4 (2 script tags)
buildClarityScript{ projectId }ScriptConfigMicrosoft Clarity
buildPostHogScript{ apiKey, apiHost? }ScriptConfigPostHog
buildPlausibleScript{ domain, customDomain? }ScriptConfigPlausible Analytics
buildFathomScript{ siteId }ScriptConfigFathom Analytics

ScriptConfig

PropTypeDescription
idstringUnique script identifier
srcstring | undefinedExternal script URL
innerHTMLstring | undefinedInline JavaScript content
asyncboolean | undefinedLoad asynchronously
deferboolean | undefinedDefer execution
consentCategoryConsentCategoryRequired consent category for loading
attributesRecord<string, string> | undefinedAdditional script attributes
shouldLoad(consent: ConsentState) => booleanReturns true if this script may load

createConsentManager(initialState)

MethodSignatureDescription
grant(category: ConsentCategory) => voidGrant a consent category
revoke(category: ConsentCategory) => voidRevoke a consent category
grantAll() => voidGrant all non-necessary categories
revokeAll() => voidRevoke all non-necessary categories
getState() => ConsentStateGet the current consent snapshot
isGranted(category: ConsentCategory) => booleanCheck if a category is granted
onChange(cb: ConsentChangeCallback) => () => voidSubscribe to changes; returns unsubscribe

API Clients

FunctionParametersReturnsDescription
createGA4Client(accessToken: string)GA4ClientGoogle Analytics 4 Data API
createClarityClient(apiKey: string)ClarityClientMicrosoft Clarity API
createPostHogClient(apiKey: string, host?: string)PostHogClientPostHog API
createPlausibleClient(apiKey: string)PlausibleClientPlausible Stats API
createFathomClient(apiKey: string)FathomClientFathom Analytics API

React Components

ComponentPropsDescription
<AnalyticsScript>{ scripts: ScriptConfig[], consent: ConsentState }Renders <script> tags that pass shouldLoad(consent)
<ConsentBanner>{ manager: ConsentManager, privacyPolicyUrl?: string }GDPR cookie consent banner with Accept All / Reject All

Types

TypeDescription
ConsentCategory'necessary' | 'analytics' | 'marketing' | 'preferences'
ConsentState{ necessary, analytics, marketing, preferences } all boolean
ConsentManagerStore with grant/revoke/grantAll/revokeAll/getState/isGranted/onChange
ConsentChangeCallback(state: ConsentState) => void
ScriptConfig{ id, src?, innerHTML?, async?, defer?, consentCategory, attributes?, shouldLoad }
GA4Config{ measurementId, consentModeV2?, anonymizeIp?, sendPageView? }
GA4ReportRequest{ startDate, endDate, metrics, dimensions?, limit? }
GA4ReportResponse{ rows, rowCount, metadata? }
GA4ClientMethods: queryReport, getRealtimeReport, getMetadata
ClarityConfig{ projectId: string }
ClarityClientMethods: getProjects, getInsights, getHeatmapData
PostHogConfig{ apiKey: string, host?: string }
PostHogClientMethods: queryEvents, getTrends, getFunnels
PlausibleConfig{ domain: string, selfHostedUrl?: string }
PlausibleClientMethods: getTimeseries, getBreakdown, getAggregate
FathomConfig{ siteId: string }
FathomClientMethods: getSites, getPageviews, getReferrers

Use Cases

  • GDPR-compliant web apps — load analytics scripts only after the user grants consent
  • SaaS marketing sites — track user behavior with GA4 while respecting privacy regulations
  • E-commerce stores — Clarity session recordings for UX optimization with a consent gate
  • Multi-provider analytics — run GA4 + Plausible + PostHog side-by-side for data validation
  • Privacy-first apps — Plausible or Fathom as cookieless, GDPR-compliant alternatives to GA4
  • Analytics dashboards — query GA4, Plausible, or Fathom APIs server-side for custom reporting
  • A/B testing pipelines — PostHog feature flags and event tracking with consent management
  • Enterprise compliance — full audit trail of when consent was granted per category

Architecture Overview

  • Pure TypeScript — no compiled binary, no native modules
  • Consent-first designshouldLoad(consentState) is evaluated before any script tag is created
  • GDPR defaultsnecessary: true always; analytics, marketing, preferences default to false
  • SSR-safe builders — script configs are generated server-side; consent is evaluated client-side
  • Edge-compatible — script builders and consent manager have no Node.js-specific APIs; runs in Cloudflare Workers, Vercel Edge, Deno
  • Optional React peer<AnalyticsScript> and <ConsentBanner> require React 18+; all other exports are framework-agnostic
  • Dual ESM + CJS — ships both formats via tsup for any bundler or require() usage
  • Zero runtime dependencies — pure TypeScript; optional React peer dependency only

Supply Chain Security

  • No install scripts (postinstall, preinstall)
  • No runtime network access outside of analytics API calls
  • No eval or dynamic code execution
  • CI-signed builds — all releases published via verified github.com/CyberCraftBD/power-seo workflow
  • Safe for SSR, Edge, and browser environments

The @power-seo Ecosystem

All 17 packages are independently installable — use only what you need.

PackageInstallDescription
@power-seo/corenpm i @power-seo/coreFramework-agnostic utilities, types, validators, and constants
@power-seo/reactnpm i @power-seo/reactReact SEO components — meta, Open Graph, Twitter Card, breadcrumbs
@power-seo/metanpm i @power-seo/metaSSR meta helpers for Next.js App Router, Remix v2, and generic SSR
@power-seo/schemanpm i @power-seo/schemaType-safe JSON-LD structured data — 23 builders + 22 React components
@power-seo/content-analysisnpm i @power-seo/content-analysisYoast-style SEO content scoring engine with React components
@power-seo/readabilitynpm i @power-seo/readabilityReadability scoring — Flesch-Kincaid, Gunning Fog, Coleman-Liau, ARI
@power-seo/previewnpm i @power-seo/previewSERP, Open Graph, and Twitter/X Card preview generators
@power-seo/sitemapnpm i @power-seo/sitemapXML sitemap generation, streaming, index splitting, and validation
@power-seo/redirectsnpm i @power-seo/redirectsRedirect engine with Next.js, Remix, and Express adapters
@power-seo/linksnpm i @power-seo/linksLink graph analysis — orphan detection, suggestions, equity scoring
@power-seo/auditnpm i @power-seo/auditFull SEO audit engine — meta, content, structure, performance rules
@power-seo/imagesnpm i @power-seo/imagesImage SEO — alt text, lazy loading, format analysis, image sitemaps
@power-seo/ainpm i @power-seo/aiLLM-agnostic AI prompt templates and parsers for SEO tasks
@power-seo/analyticsnpm i @power-seo/analyticsMerge GSC + audit data, trend analysis, ranking insights, dashboard
@power-seo/search-consolenpm i @power-seo/search-consoleGoogle Search Console API — OAuth2, service account, URL inspection
@power-seo/integrationsnpm i @power-seo/integrationsSemrush and Ahrefs API clients with rate limiting and pagination
@power-seo/trackingnpm i @power-seo/trackingGA4, Clarity, PostHog, Plausible, Fathom — scripts + consent management

About CyberCraft Bangladesh

CyberCraft Bangladesh is a Bangladesh-based enterprise-grade software development and Full Stack SEO service provider 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.

Website GitHub npm Email

© 2026 CyberCraft Bangladesh · Released under the MIT License

Keywords

seo

FAQs

Package last updated on 05 Apr 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts