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

FilePurpose
components/features/analytics/analytics-provider.tsxReact provider — injects PostHog + GA scripts on mount
lib/features/analytics.tstrackEvent(), identify(), pageView() helper functions

Setup

1

Install dependencies

pnpm add posthog-js

Google 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

VariableRequiredDescription
NEXT_PUBLIC_POSTHOG_KEYNoPostHog project API key
NEXT_PUBLIC_GA_IDNoGoogle Analytics measurement ID (G-...)

Verification

  1. Set NEXT_PUBLIC_POSTHOG_KEY and restart dev server
  2. Open PostHog → Live Events — navigate your app and watch $pageview events appear
  3. For GA: open GA → Realtime → Overview — navigate and confirm active users
  4. 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 AnalyticsProvider rendering behind a consent banner.

Demo Mode — Explore freely. Some actions are restricted. demo@launchfst.dev / demo1234

Get LaunchFst →