dinaf2026-web/awesome-web-skills/web-analytics

Claude Code and agent skill by dinaf2026-web/awesome-web-skills

Trust tier 2
  • community
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

Analytics and event tracking patterns for modern web apps — GA4, PostHog, Vercel Analytics, and custom event tracking. Know what users actually do on your site.

Install

npx vskill@latest install dinaf2026-web/awesome-web-skills/web-analytics

SKILL.md

The same SKILL.md was published earlier as dinaf2026-web/awesome-web-skills/web-analytics.

Web Analytics

Analytics and event tracking patterns for modern web apps. GA4, PostHog, Vercel Analytics, and custom event systems — set up once, trust forever.


1. When to Use Which

ToolBest ForPricingSelf-HostAutocaptureSession Recording
Vercel AnalyticsNext.js perf + Web Vitals, zero-configFree tier generousNoNoNo
GA4Marketing attribution, Google Ads, SEO reportingFreeNoLimitedNo
PostHogProduct analytics, funnels, feature flags, session replayGenerous free tierYesYesYes
PlausiblePrivacy-first page stats, GDPR out of the box$9/moYesNoNo

Decision rules:

  • Solo project / side project → Vercel Analytics + Plausible. Done.
  • SaaS product that needs funnels, retention, feature flags → PostHog.
  • Marketing site with Google Ads spend → GA4. You need conversion attribution.
  • Enterprise with strict data residency → PostHog self-hosted.
  • Use PostHog + Vercel Analytics together. They solve different problems.

2. Vercel Analytics Setup

Zero-config Web Vitals. Add it and forget it.

bash
npm install @vercel/analytics @vercel/speed-insights
Root Layout
tsx
// app/layout.tsx
import { Analytics } from '@vercel/analytics/react'
import { SpeedInsights } from '@vercel/speed-insights/next'
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
{children}
<Analytics />
<SpeedInsights />
</body>
</html>
)
}
Custom Events
tsx
// lib/analytics/vercel.ts
import { track } from '@vercel/analytics'
export function trackVercel(event: string, properties?: Record<string, string | number | boolean>) {
track(event, properties)
}
tsx
// Usage in a component
import { trackVercel } from '@/lib/analytics/vercel'
function SignupButton() {
return (
<button
onClick={() => {
trackVercel('signup_clicked', { plan: 'pro', source: 'hero' })
}}
>
Get Started
</button>
)
}

Vercel Analytics custom events appear in your Vercel dashboard under the Events tab. Properties must be strings, numbers, or booleans — no nested objects.


3. GA4 Setup in Next.js (App Router)

Install

No package needed. GA4 loads via Google's script tag.

Environment Variable
bash
# .env.local
NEXT_PUBLIC_GA_MEASUREMENT_ID=G-XXXXXXXXXX
Script Component — Root Layout
tsx
// app/layout.tsx
import Script from 'next/script'
const GA_ID = process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
{GA_ID && (
<>
<Script
src={`https://www.googletagmanager.com/gtag/js?id=${GA_ID}`}
strategy="afterInteractive"
/>
<Script id="google-analytics" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_ID}', {
page_path: window.location.pathname,
anonymize_ip: true,
cookie_flags: 'SameSite=None;Secure'
});
`}
</Script>
</>
)}
</head>
<body>{children}</body>
</html>
)
}
GA4 Wrapper
tsx
// lib/analytics/ga4.ts
declare global {
interface Window {
gtag: (...args: unknown[]) => void
dataLayer: unknown[]
}
}
const GA_ID = process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID
export function pageview(url: string) {
if (!GA_ID || typeof window === 'undefined') return
window.gtag('config', GA_ID, { page_path: url })
}
export function gtagEvent(
action: string,
params: {
category?: string
label?: string
value?: number
[key: string]: unknown
} = {}
) {
if (!GA_ID || typeof window === 'undefined') return
window.gtag('event', action, params)
}
Pageview Tracking on Route Changes (App Router)

App Router handles navigation differently from Pages Router. Use a client component that listens to pathname changes.

tsx
// components/analytics/GoogleAnalytics.tsx
'use client'
import { usePathname, useSearchParams } from 'next/navigation'
import { useEffect } from 'react'
import { pageview } from '@/lib/analytics/ga4'
export function GoogleAnalytics() {
const pathname = usePathname()
const searchParams = useSearchParams()
useEffect(() => {
const url = pathname + (searchParams.toString() ? `?${searchParams.toString()}` : '')
pageview(url)
}, [pathname, searchParams])
return null
}
tsx
// app/layout.tsx — add inside <body>
import { Suspense } from 'react'
import { GoogleAnalytics } from '@/components/analytics/GoogleAnalytics'
// Wrap in Suspense — useSearchParams requires it in App Router
<Suspense fallback={null}>
<GoogleAnalytics />
</Suspense>

4. PostHog Setup

Full product analytics: autocapture, funnels, session recording, feature flags.

bash
npm install posthog-js posthog-node
Environment Variables
bash
NEXT_PUBLIC_POSTHOG_KEY=phc_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com
# For server-side: use the same key, PostHog Node uses it directly
Client Provider
tsx
// components/analytics/PostHogProvider.tsx
'use client'
import posthog from 'posthog-js'
import { PostHogProvider as PHProvider } from 'posthog-js/react'
import { useEffect } from 'react'
export function PostHogProvider({ children }: { children: React.ReactNode }) {
useEffect(() => {
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
person_profiles: 'identified_only', // only create profiles for identified users
capture_pageview: false, // handle manually for App Router
capture_pageleave: true,
session_recording: {
maskAllInputs: true, // mask form inputs in recordings
maskInputOptions: { password: true },
},
loaded: (ph) => {
if (process.env.NODE_ENV === 'development') {
ph.opt_out_capturing() // don't pollute prod data with dev events
}
},
})
}, [])
return <PHProvider client={posthog}>{children}</PHProvider>
}
Pageview Tracking
tsx
// components/analytics/PostHogPageview.tsx
'use client'
import { usePathname, useSearchParams } from 'next/navigation'
import { useEffect } from 'react'
import { usePostHog } from 'posthog-js/react'
export function PostHogPageview() {
const pathname = usePathname()
const searchParams = useSearchParams()
const posthog = usePostHog()
useEffect(() => {
if (!posthog) return
const url = window.origin + pathname + (searchParams.toString() ? `?${searchParams.toString()}` : '')
posthog.capture('$pageview', { $current_url: url })
}, [pathname, searchParams, posthog])
return null
}
Root Layout Integration
tsx
// app/layout.tsx
import { Suspense } from 'react'
import { PostHogProvider } from '@/components/analytics/PostHogProvider'
import { PostHogPageview } from '@/components/analytics/PostHogPageview'
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<PostHogProvider>
<Suspense fallback={null}>
<PostHogPageview />
</Suspense>
{children}
</PostHogProvider>
</body>
</html>
)
}
Server-Side PostHog (API Routes, Server Actions)
tsx
// lib/analytics/posthog-server.ts
import { PostHog } from 'posthog-node'
let _client: PostHog | null = null
export function getPostHogServer(): PostHog {
if (!_client) {
_client = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
flushAt: 1, // flush immediately in serverless
flushInterval: 0,
})
}
return _client
}
// Always shut down after serverless invocation
export async function shutdownPostHog() {
if (_client) {
await _client.shutdown()
_client = null
}
}

5. Custom Event Tracking Pattern

Type-safe, centralized event system. One place to change event names. No magic strings scattered across components.

Define Your Event Catalog
tsx
// lib/analytics/events.ts
// All events your app can emit — add new ones here only
export type AnalyticsEvent =
// Auth
| { name: 'signup_started'; properties: { source: string; plan?: string } }
| { name: 'signup_completed'; properties: { plan: string; method: 'email' | 'google' | 'github' } }
| { name: 'login'; properties: { method: 'email' | 'google' | 'github' } }
| { name: 'logout'; properties: Record<string, never> }
// Billing
| { name: 'upgrade_clicked'; properties: { from_plan: string; to_plan: string; trigger: string } }
| { name: 'checkout_started'; properties: { plan: string; price: number; currency: string } }
| { name: 'payment_completed'; properties: { plan: string; price: number; currency: string } }
| { name: 'payment_failed'; properties: { plan: string; error_code: string } }
// Feature usage
| { name: 'feature_used'; properties: { feature: string; context?: string } }
| { name: 'export_triggered'; properties: { format: 'csv' | 'pdf' | 'json'; record_count: number } }
// Engagement
| { name: 'onboarding_step_completed'; properties: { step: number; step_name: string } }
| { name: 'search_performed'; properties: { query: string; results_count: number } }
| { name: 'error_encountered'; properties: { error_type: string; page: string } }
Centralized track() Function
tsx
// lib/analytics/track.ts
import posthog from 'posthog-js'
import { gtagEvent } from './ga4'
import { trackVercel } from './vercel'
import type { AnalyticsEvent } from './events'
export function track<T extends AnalyticsEvent>(
event: T['name'],
properties: Extract<T, { name: T['name'] }>['properties']
) {
// PostHog
if (typeof window !== 'undefined') {
posthog.capture(event, properties)
}
// GA4 — map to GA4 event structure
gtagEvent(event, properties as Record<string, unknown>)
// Vercel — flatten to primitives only
const flatProps = flattenForVercel(properties)
trackVercel(event, flatProps)
}
// Vercel only accepts string | number | boolean values
function flattenForVercel(
obj: Record<string, unknown>
): Record<string, string | number | boolean> {
return Object.fromEntries(
Object.entries(obj)
.filter(([, v]) => ['string', 'number', 'boolean'].includes(typeof v))
.map(([k, v]) => [k, v as string | number | boolean])
)
}
Usage
tsx
// Anywhere in your app — fully typed, autocompletes
import { track } from '@/lib/analytics/track'
// TypeScript enforces correct properties for each event name
track('signup_completed', {
plan: 'pro',
method: 'google',
})
track('export_triggered', {
format: 'csv',
record_count: 1482,
})
// Type error — 'method' is required for signup_completed
// track('signup_completed', { plan: 'pro' }) // ❌ TS error

6. Funnel Tracking

Funnels only work if every step fires the right event with consistent properties. Define the funnel events before building the feature.

Signup Funnel
Landing page visit → CTA clicked → Signup form viewed → Email entered →
Plan selected → Payment entered → Account created → Onboarding step 1 → ... → Activated
tsx
// lib/analytics/funnels/signup.ts
import { track } from '@/lib/analytics/track'
export const signupFunnel = {
ctaClicked: (source: string, plan?: string) =>
track('signup_started', { source, plan }),

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
0

Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/dinaf2026-web/awesome-web-skills/web-analytics/badge)](https://verified-skill.com/skills/dinaf2026-web/awesome-web-skills/web-analytics)

Something wrong with this skill or its page? Tell us.