Use PostHog Analytics
Learn how to track events with PostHog analytics
Learn how to track custom events with PostHog analytics in your Plainform application.
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:
'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:
'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:
'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:
- Go to app.posthog.com
- Navigate to Events to see all tracked events
- 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
useEffectwith proper dependencies
Next Steps
- Change Colors - Customize color scheme
- Add Font - Customize typography
Related Documentation
- PostHog Docs - Complete PostHog documentation
- PostHog React - React integration guide
How is this guide ?
Last updated on