Use PostHog Analytics

Learn how to track events with PostHog analytics in Plainform

Learn how to track custom events with PostHog analytics in your Plainform application.

Full Analytics Setup: For complete analytics configuration including Google Analytics 4 and PostHog setup, see the Analytics Setup Guide.

Goal

By the end of this recipe, you'll have added custom event tracking to your application.

Prerequisites

  • A working Plainform installation
  • PostHog configured (already set up in Plainform)

Steps

Track Events in Client Components

Use the usePostHog hook to track events:

components/YourComponent.tsx
'use client';

import { usePostHog } from 'posthog-js/react';

export function YourComponent() {
  const posthog = usePostHog();

  const handleClick = () => {
    posthog.capture('button_clicked', {
      button_name: 'cta_signup',
      page: window.location.pathname,
    });
  };

  return <button onClick={handleClick}>Sign Up</button>;
}

Track Page Views

Page views are automatically tracked. To track custom page properties:

app/your-page/page.tsx
'use client';

import { usePostHog } from 'posthog-js/react';
import { useEffect } from 'react';

export default function YourPage() {
  const posthog = usePostHog();

  useEffect(() => {
    posthog.capture('$pageview', {
      page_type: 'pricing',
      plan_shown: 'pro',
    });
  }, [posthog]);

  return <div>Your content</div>;
}

Identify Users

Identify users after sign-in:

components/user/SignInForm.tsx
'use client';

import { usePostHog } from 'posthog-js/react';
import { useUser } from '@clerk/nextjs';
import { useEffect } from 'react';

export function UserIdentifier() {
  const posthog = usePostHog();
  const { user } = useUser();

  useEffect(() => {
    if (user) {
      posthog.identify(user.id, {
        email: user.emailAddresses[0]?.emailAddress,
        name: user.fullName,
      });
    }
  }, [user, posthog]);

  return null;
}

View Analytics

Visit your PostHog dashboard to view tracked events:

  1. Go to app.posthog.com
  2. Navigate to Events to see all tracked events
  3. Create Insights to visualize your data

Common Event Types

Track these common events:

// Button clicks
posthog.capture('button_clicked', { button_name: 'cta' });

// Form submissions
posthog.capture('form_submitted', { form_name: 'contact' });

// Feature usage
posthog.capture('feature_used', { feature_name: 'export' });

// Purchases
posthog.capture('purchase_completed', { amount: 99, plan: 'pro' });

Common Issues

Events Not Appearing

  • Check PostHog API key in .env.local
  • Verify PostHog provider is wrapping your app
  • Check browser console for errors

Duplicate Events

  • Ensure event tracking is not in a component that re-renders frequently
  • Use useEffect with proper dependencies

Next Steps

How is this guide ?

Last updated on

On this page