Analytics
Drop-in analytics with PostHog and Google Analytics. Zero overhead when env vars are not set.
Add PostHog and/or Google Analytics to your app in ~5 minutes. Both providers are optional — the AnalyticsProvider only loads scripts when the corresponding env var is present.
What's Included
| File | Purpose |
|---|---|
components/features/analytics/analytics-provider.tsx | React provider — injects PostHog + GA scripts on mount |
lib/features/analytics.ts | trackEvent(), identify(), pageView() helper functions |
Setup
1
Install dependencies
pnpm add posthog-jsGoogle Analytics uses a gtag.js script tag — no npm package needed.
2
Add environment variables
# PostHog — get from app.posthog.com → Project Settings → API Keys
NEXT_PUBLIC_POSTHOG_KEY="phc_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# Google Analytics — get from analytics.google.com → Admin → Data Streams
NEXT_PUBLIC_GA_ID="G-XXXXXXXXXX"Both are optional. Set neither and the provider renders children with zero overhead.
3
Add the provider
Wrap your app or marketing layout:
// app/(marketing)/layout.tsx
import { AnalyticsProvider } from "@/components/features/analytics/analytics-provider"
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<AnalyticsProvider>{children}</AnalyticsProvider>
</body>
</html>
)
}4
Track custom events
import { trackEvent, identify, pageView } from "@/lib/features/analytics"
// Custom event
trackEvent("button_clicked", { variant: "cta", page: "/pricing" })
// Identify a user after sign-in
identify(user.id, { email: user.email, plan: user.plan })
// Manual page view (AnalyticsProvider handles this automatically)
pageView()Environment Variables
| Variable | Required | Description |
|---|---|---|
NEXT_PUBLIC_POSTHOG_KEY | No | PostHog project API key |
NEXT_PUBLIC_GA_ID | No | Google Analytics measurement ID (G-...) |
Verification
- Set
NEXT_PUBLIC_POSTHOG_KEYand restart dev server - Open PostHog → Live Events — navigate your app and watch
$pageviewevents appear - For GA: open GA → Realtime → Overview — navigate and confirm active users
- Remove both env vars — confirm no analytics scripts load (Network tab)
Notes
- PostHog is the primary provider. If both are set, events fire to both.
- Scripts load after mount (client-side only).
- For GDPR compliance, gate
AnalyticsProviderrendering behind a consent banner.