Welcome! Analytics doesn't have to be scary. This guide helps you add privacy-first analytics to your Next.js project in 5 minutes. No complex coding required—just copy and paste our AI prompts.
🛠️ Preparation
- Open your AI Editor: Cursor, Antigravity, or Copilot.
- Get PostHog: Sign up at posthog.com (it's free).
- Get your Key: After signing up, copy your Project API Key and Host URL.
🟢 Step 1: Install the "Camera"
First, we need to install the basic tracking so you can see who is visiting your site. Copy this prompt to your AI:
**Role**: Senior Frontend Engineer
**Objective**: Integrate PostHog Analytics into a Next.js (App Router) project with a focus on **User Privacy**.
**Context**:
- We use Next.js App Router.
- We want to use `posthog-js`.
- **Privacy Rule**: Do NOT track users anonymously by default. Use `person_profiles: 'identified_only'`. Only track profiles if we explicitly identify them (e.g., after login).
**Action Plan**:
1. **Install**: Run `npm install posthog-js`.
2. **Env**: Add `NEXT_PUBLIC_POSTHOG_KEY` and `NEXT_PUBLIC_POSTHOG_HOST` to `.env.local`.
3. **Singleton**: Create `lib/analytics/client.ts`.
- Export `initAnalytics()` that initializes PostHog only once (check `window`).
- Enable `debug: true` only in development.
4. **Provider**: Create `components/analytics/AnalyticsProvider.tsx`.
- Use `'use client'`.
- Wrap logic in `Suspense` to avoid de-opting Static Rendering.
- Calls `initAnalytics()` on mount.
- **Pageview Tracking**: Since Next.js App Router doesn't have router events, use `usePathname` and `useSearchParams` in a `useEffect` to manually capture `$pageview` events.
5. **Layout**: Tell me how to add this Provider to `app/layout.tsx`.
🟡 Step 2: Track Buttons (The Fun Part)
Knowing people are visiting is good. Knowing what they click is better. Let's track a specific button, like "Buy Now" or "Vote".
Copy this prompt to your AI:
**Role**: Product Engineer
**Objective**: Implement "Event Tracking" for a specific button interaction.
**Task**:
1. Teach me how to use the PostHog `capture` method.
2. Example: I want to track a 'Vote' button.
3. Write a code snippet for a Button component that sends this event when clicked:
- Event Name: `clicked_vote`
- Properties: `{ item_id: '123', item_name: 'My Product' }`
4. Make sure to import PostHog dynamically (Dynamic Import) so it doesn't slow down the page load.
✅ Step 3: Check Your Data
- Check Env Vars: Make sure your Key and Host are saved in
.env.local. - Disable AdBlock: If you use uBlock Origin, pause it for localhost.
- See it Live: Go to PostHog Dashboard -> Activity or Live Events.
- Click Around: Click buttons on your site and watch the events pop up instantly!
That's it! 🚀 You now have cleaner data than 90% of websites out there.