Skip to main content

How I Tracked My Students' Journey with PostHog

How I Tracked My Students' Journey with PostHog
tips#PostHog#Product Analytics#User Behavior Tracking#Next.js Analytics+12 more

How I Tracked My Students' Journey with PostHog

Learn how PostHog helped me track student behavior, identify conversion issues, and increase my course conversion rate by 133%. Complete Next.js integration guide with real examples.

Mohammad Alhabil

Author

January 7, 2026
13 min read
~2600 words

From Click to Success: How I Tracked My Students' Journey with PostHog 🎯

In my previous blog, we talked about the magic of UTM parameters and how I discovered where my students came from. But knowing the traffic source is just the beginning.

The real question is: What happens after a student clicks the link?

  • Do they complete registration?
  • Or do they abandon halfway through?
  • Where exactly do they get stuck?

This is where I discovered PostHog, and it completely transformed my understanding of user behavior.


Beyond Traditional Analytics: Why PostHog?

Traditional analytics tools like Google Analytics tell you what happened (pageviews, sessions, bounce rates). But they don't tell you why it happened or show you the actual user experience.

PostHog goes beyond numbersβ€”it helps you understand behavior through:

The Key Differences

Traditional Analytics (Google Analytics):

  • Shows aggregate metrics (total visits, bounce rate)
  • Requires manual event setup for everything
  • Limited visibility into user behavior
  • Can't see actual user sessions
  • Data lives on Google's servers

PostHog:

  • Captures every interaction automatically (autocapture)
  • Shows actual user sessions with recordings
  • Visualizes user paths with funnels and heatmaps
  • Self-hostable with full data ownership
  • Open source with transparent development

Since I was building my course platform with Next.js, the integration was surprisingly smooth and fast.


Smart Setup with Next.js and AI-Powered Autocapture

One of PostHog's most powerful features is its intelligent autocapture. PostHog automatically analyzes your Next.js project and identifies critical interaction points like registration buttons, payment forms, and navigation linksβ€”then captures these events without manual instrumentation.

How Autocapture Works

By default, posthog-js automatically captures pageviews, element clicks, inputs, form submissions, and more. This means you get immediate value without writing a single line of tracking code.

What gets autocaptured:

  • βœ… Page views and navigation
  • βœ… Button clicks and link clicks
  • βœ… Form submissions and inputs
  • βœ… Element visibility and interactions
  • βœ… Session duration and engagement

Next.js Integration: Step by Step

Let's walk through the complete setup process.

Step 1: Install PostHog

Install the required packages:

npm install posthog-js

Step 2: Create Environment Variables

Add your PostHog credentials to .env.local:

NEXT_PUBLIC_POSTHOG_KEY=phc_your_project_api_key
NEXT_PUBLIC_POSTHOG_HOST=https://app.posthog.com

You can find these values in your PostHog project settings.

Step 3: Create PostHog Provider (App Router)

For Next.js apps using the app router, create a providers file in your app folder since posthog-js needs to be initialized on the client-side using the 'use client' directive.

Create app/providers.tsx:

'use client';

import posthog from 'posthog-js';
import { PostHogProvider } from 'posthog-js/react';
import { useEffect } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';

if (typeof window !== 'undefined') {
  posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
    api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
    person_profiles: 'identified_only', // or 'always'
    capture_pageview: false, // We'll capture manually
    capture_pageleave: true,
    
    // Enable session recording
    session_recording: {
      recordCrossOriginIframes: true,
    },
  });
}

export function PHProvider({ children }: { children: React.ReactNode }) {
  return <PostHogProvider client={posthog}>{children}</PostHogProvider>;
}

// Component to track page views
export function PostHogPageView() {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    if (pathname && posthog) {
      let url = window.origin + pathname;
      if (searchParams.toString()) {
        url = url + `?${searchParams.toString()}`;
      }
      
      posthog.capture('$pageview', {
        $current_url: url,
      });
    }
  }, [pathname, searchParams]);

  return null;
}

Step 4: Update Root Layout

Wrap your app with the PostHog provider in app/layout.tsx:

import { PHProvider, PostHogPageView } from './providers';
import { Suspense } from 'react';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <PHProvider>
          <Suspense fallback={null}>
            <PostHogPageView />
          </Suspense>
          {children}
        </PHProvider>
      </body>
    </html>
  );
}

Step 5: Capture Custom Events (Optional)

While autocapture handles most interactions, you can manually capture specific events:

'use client';

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

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

  const handleRegister = () => {
    // Capture custom event with properties
    posthog.capture('course_registration_started', {
      course_name: 'Advanced Next.js',
      price: '$99',
      source: 'landing_page',
    });
    
    // Navigate to the registration page
    router.push('/register');
  };

  return (
    <button onClick={handleRegister}>
      Register Now
    </button>
  );
}

That's it! After setup and restart, PostHog starts autocapturing events and pageviews. If session replays are enabled in project settings, those are captured too.


What I Discovered with PostHog's Features

1. Session Recording β€” Watching Real User Behavior

Session recording was the game-changer. I could literally watch recordings of how students interacted with my course page.

What I saw:

  • Where students clicked and what they expected to happen
  • Which sections they read carefully vs. scrolled past quickly
  • Where they got confused or stuck
  • Mobile vs. desktop behavior differences

Real Example:

I noticed students from LinkedIn ads were dropping off at the payment page. When I watched their session recordings, I discovered:

  • The payment form wasn't responsive on mobile
  • The "Pay Now" button was hidden below the fold on small screens
  • Users were trying to click a disabled button (poor UX feedback)

The Fix:

// Before: Button hidden on mobile
<div className="payment-form">
  <input type="text" placeholder="Card Number" />
  <input type="text" placeholder="Expiry Date" />
  <input type="text" placeholder="CVV" />
  {/* Button was way down here, invisible on mobile */}
  <button>Pay Now</button>
</div>

// After: Fixed layout with visible CTA
<div className="payment-form max-w-md mx-auto">
  <input 
    type="text" 
    placeholder="Card Number"
    className="w-full mb-4 p-3 border rounded-lg"
  />
  <div className="grid grid-cols-2 gap-4 mb-4">
    <input type="text" placeholder="Expiry" className="p-3 border rounded-lg" />
    <input type="text" placeholder="CVV" className="p-3 border rounded-lg" />
  </div>
  {/* Sticky button always visible */}
  <button className="w-full bg-blue-600 text-white py-4 rounded-lg font-semibold sticky bottom-0">
    Complete Payment
  </button>
</div>

Result: Mobile conversion rate increased by 35%.

2. Conversion Funnels β€” Identifying Drop-off Points

I created a registration funnel to track the complete student journey:

My Funnel Steps:

  1. Landing page view β†’ Initial interest
  2. Course details viewed β†’ Exploring content
  3. "Register Now" clicked β†’ Intent to purchase
  4. Payment form started β†’ Committed
  5. Registration completed β†’ Success! πŸŽ‰

The Shocking Discovery:

Nearly 30% of students were dropping off at the payment step. This was a critical leak in my funnel.

Setting Up a Funnel in PostHog:

  1. Go to Insights β†’ Funnels
  2. Click New Insight β†’ Funnel
  3. Define your steps:
Step 1: Pageview where URL contains /course
Step 2: Autocapture click on "View Course Details"
Step 3: Autocapture click on "Register Now"
Step 4: Pageview where URL contains /payment
Step 5: Custom event: course_registration_completed
  1. Add breakdown dimensions:
    • utm_source β†’ Which platform performs best?
    • utm_campaign β†’ Which campaign converts better?
    • Device type β†’ Mobile vs. Desktop differences?

What the Data Revealed:

Funnel StepOverallLinkedInFacebookInstagram
Landing Page100%100%100%100%
Details Viewed65%78%55%48%
Register Clicked42%58%35%28%
Payment Started28%41%22%15%
Completed20%35%15%8%

Key Insights:

  • LinkedIn traffic converts 4x better than Instagram
  • Instagram users rarely make it past the details page
  • Facebook users drop off most at the payment step

3. Heatmaps β€” Understanding Attention Patterns

Heatmaps showed me exactly what content students paid attention to on my course landing page.

What I Discovered:

High Engagement Areas (Hot Zones):

  • Course curriculum section (85% of users scrolled here)
  • Student testimonials (72% read at least one)
  • Pricing information (95% viewed)
  • Instructor bio (only 35% scrolled to this)

Low Engagement Areas (Cold Zones):

  • Long text paragraphs (most users skipped)
  • FAQ section at the bottom (only 20% reached it)
  • Detailed course schedule (18% engagement)

Content Restructure Based on Heatmap Data:

// Before: Long paragraphs, FAQs at the bottom
<section>
  <h2>About This Course</h2>
  <p>Long paragraph...</p>
  <p>More text...</p>
  {/* Course details buried here */}
</section>
{/* FAQs way down at the bottom */}

// After: Scannable, prioritized content
<section className="space-y-12">
  {/* 1. Immediate value proposition */}
  <Hero />
  
  {/* 2. What students care about most */}
  <CourseOutline />
  
  {/* 3. Social proof */}
  <Testimonials />
  
  {/* 4. Clear pricing */}
  <PricingSection />
  
  {/* 5. Move FAQs up - address objections early */}
  <FAQ />
  
  {/* 6. Instructor bio (now less critical) */}
  <InstructorBio />
</section>

Result: Average time on page increased by 40%, and scroll depth improved significantly.

4. UTM Integration β€” Connecting Traffic Source to Behavior

PostHog automatically captures UTM parameters, allowing me to segment user behavior by traffic source.

Behavioral Differences by Platform:

LinkedIn Users (Highest Quality):

  • Read course details thoroughly (avg. 8 minutes on page)
  • Engaged with the curriculum section (90% scrolled through it)
  • Highest conversion rate (35%)
  • Lower cart abandonment

Facebook Users (Price-Sensitive):

  • Immediately scrolled to pricing (95% within 10 seconds)
  • Skipped course details (only 35% read them)
  • Medium conversion rate (15%)
  • High drop-off at the payment step

Instagram Users (Low Intent):

  • Fast scrollers (avg. 2 minutes on page)
  • Focused on images and testimonials
  • Lowest conversion rate (8%)
  • Most likely to bounce

Adjusting Strategy by Platform:

Based on these insights, I customized my approach:

For LinkedIn:

  • Longer, educational posts with detailed course info
  • Emphasize professional growth and career advancement
  • Target senior professionals and decision-makers

For Facebook:

  • Lead with pricing and value proposition
  • Highlight payment plans and discounts
  • Use urgency tactics (limited-time offers)

For Instagram:

  • Focus on awareness and engagement, not direct sales
  • Use Stories to share course previews and student wins
  • Drive traffic to email signup, not direct purchase

Advanced PostHog Features I Use

Feature Flags for A/B Testing

Test different versions of your landing page without deploying code:

'use client';

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

export function CoursePricingSection() {
  // Test: Show discount badge or not
  const showDiscount = useFeatureFlagEnabled('show-discount-badge');
  
  return (
    <div className="pricing-card">
      <h3>Course Price: $99</h3>
      {showDiscount && (
        <span className="discount-badge">
          πŸŽ‰ 20% OFF - Limited Time!
        </span>
      )}
      <button>Enroll Now</button>
    </div>
  );
}

How it works:

  1. Create a feature flag in the PostHog dashboard
  2. Set rollout percentage (e.g., 50% of users see the discount)
  3. Compare conversion rates between variants
  4. Roll out winning variant to 100%

My A/B Test Results:

  • Variant A (no discount badge): 18% conversion
  • Variant B (with discount badge): 26% conversion
  • Winner: Variant B (+44% improvement)

Cohort Analysis

Group users by behavior and compare performance:

// Create cohorts in the PostHog dashboard:

// Cohort 1: "High Intent Users"
// - Viewed course details
// - Spent > 5 minutes on page
// - Clicked "Register Now"

// Cohort 2: "Price Shoppers"
// - Scrolled directly to pricing
// - Spent < 2 minutes on page
// - Didn't view curriculum

// Cohort 3: "Mobile Browsers"
// - Device type = mobile
// - Any engagement level

Insights from Cohorts:

  • High Intent Users convert at 45% (vs. 20% overall)
  • Price Shoppers need more trust signals (testimonials, guarantees)
  • Mobile Browsers need a simplified checkout flow

Custom Dashboards

I created a live dashboard monitoring:

  • Real-time registrations (updated every 5 seconds)
  • Top traffic sources (by UTM parameters)
  • Conversion funnel (daily vs. weekly comparison)
  • Revenue by campaign (which ads are profitable)
  • Drop-off alerts (notify me if conversion drops below 15%)

Comparing PostHog to Other Analytics Tools

PostHog vs. Google Analytics

FeaturePostHogGoogle Analytics 4
Session Recordingβœ… Built-in❌ Requires separate tool
Autocaptureβœ… Yes❌ Manual event setup
Heatmapsβœ… Yes❌ No
Feature Flagsβœ… Yes❌ No
Self-Hostingβœ… Yes❌ Cloud only
Open Sourceβœ… Yes❌ No
UTM Trackingβœ… Automaticβœ… Automatic
Funnel Analysisβœ… Advancedβœ… Basic
Learning CurveMediumSteep
Free Tier1M events/monthUnlimited (with limits)

PostHog vs. Mixpanel

FeaturePostHogMixpanel
Session Recordingβœ… Yes❌ No
PricingFree up to 1M eventsExpensive (starts at $20/month)
User PrivacySelf-hostableCloud only
Setup ComplexityEasyMedium
Event TrackingAutocapture + ManualManual only
Funnel Analysisβœ… Yesβœ… Yes
Cohort Analysisβœ… Yesβœ… Yes
A/B Testingβœ… Built-in❌ Requires integration

PostHog vs. Hotjar

FeaturePostHogHotjar
Session Recordingβœ… Yesβœ… Yes
Heatmapsβœ… Yesβœ… Yes
Event Analyticsβœ… Advanced❌ Limited
Funnelsβœ… Yes❌ No
Feature Flagsβœ… Yes❌ No
PricingFree tier generousLimited free tier
All-in-Oneβœ… Yes❌ Analytics separate

My Verdict: PostHog is the best all-in-one solution for startups and developers who want full control over their data without paying enterprise prices.


Why I Chose PostHog

1. Open Source and Self-Hostable

Your data stays on your infrastructure. No third-party data sharing concerns.

2. Complete Control

Unlike SaaS-only tools, I can:

  • Self-host if my project grows
  • Customize features via their open-source codebase
  • Avoid vendor lock-in

3. All Tools in One Place

Instead of paying for:

  • Google Analytics (traffic)
  • Hotjar (heatmaps & recordings)
  • Optimizely (A/B testing)
  • LaunchDarkly (feature flags)

I get everything in PostHog.

4. Generous Free Tier

PostHog Free Plan Includes:

  • 1 million events per month
  • Unlimited session recordings (up to storage limits)
  • Unlimited feature flags
  • Full funnel and cohort analysis
  • Community support

For my course launch, this was more than enough. I only hit 300K events in my first month.


Real Results: Before and After PostHog

Before PostHog

  • ❌ Guessing why users weren't converting
  • ❌ No idea where the payment page issues were
  • ❌ Publishing content without knowing what users cared about
  • ❌ Treating all traffic sources the same way

Conversion Rate: 12%

After PostHog

  • βœ… Saw exactly where users got stuck (session recordings)
  • βœ… Fixed mobile payment UX issues
  • βœ… Restructured landing page based on heatmap data
  • βœ… Customized marketing strategy per platform

Conversion Rate: 28% (+133% improvement)

Other Wins:

  • 40% reduction in wasted ad spend
  • 35% increase in mobile conversions
  • 50% faster iteration cycles (data-driven decisions)
  • 3x better targeting on LinkedIn

Getting Started with PostHog: Action Plan

Step 1: Sign Up and Create a Project

  1. Go to posthog.com
  2. Sign up for free (no credit card required)
  3. Create a new project
  4. Copy your API key and host URL

Step 2: Integrate with Your Next.js App

Follow the integration steps outlined earlier in this post.

Step 3: Enable Session Recordings

  1. Go to Project Settings β†’ Recordings
  2. Toggle on Record user sessions
  3. Set recording filters (optional - e.g., only record registered users)

Step 4: Create Your First Funnel

  1. Navigate to Insights β†’ Funnels
  2. Define your conversion steps
  3. Add UTM breakdowns
  4. Save and monitor

Step 5: Watch Session Recordings

  1. Go to Recordings
  2. Filter by:
    • Users who dropped off in the funnel
    • Specific UTM sources
    • Mobile vs. desktop
  3. Watch and take notes

Step 6: Make Data-Driven Changes

Based on insights:

  • Fix UX issues revealed in recordings
  • Restructure content based on heatmaps
  • Optimize funnel drop-off points
  • Customize messaging per traffic source

Common Mistakes to Avoid

Mistake 1: Not Watching Enough Session Recordings

Many people set up PostHog but never watch recordings. This is where the gold is.

Solution: Block 1 hour per week to watch 10-20 session recordings of users who dropped off.

Mistake 2: Tracking Too Many Custom Events

Autocapture handles 90% of tracking. Don't overcomplicate with dozens of manual events.

Solution: Only track custom events for business-critical actions like:

  • Purchase completed
  • Trial started
  • Subscription upgraded

Mistake 3: Ignoring Mobile vs. Desktop Differences

Mobile behavior is drastically different. Analyze them separately.

Solution: Always add "Device Type" as a breakdown dimension in your funnels.

Mistake 4: Not Acting on Insights

Data without action is worthless.

Solution: Create a weekly review process:

  • Monday: Review funnel drop-offs
  • Wednesday: Watch session recordings
  • Friday: Implement one improvement

The Bottom Line

PostHog transformed my course launch from guesswork to data-driven optimization. By combining UTM tracking (from my previous post) with PostHog's powerful features, I now have complete visibility into:

βœ… Where students come from (UTM parameters)
βœ… What they do on my site (Session recordings)
βœ… Where they get stuck (Conversion funnels)
βœ… What content resonates (Heatmaps)
βœ… How to improve continuously (A/B testing with feature flags)

The result? I reduced wasted ad spend by 40%, increased conversion rates by 133%, and built a system that gets better every week.

Your Next Steps

  1. Install PostHog in your Next.js app (takes 15 minutes)
  2. Enable session recordings and watch 10 user sessions
  3. Create your first funnel to identify drop-off points
  4. Make one change based on what you learn
  5. Measure the impact and iterate

Further Reading and Resources

PostHog Resources

Comparison Guides

Topics covered

#PostHog#Product Analytics#User Behavior Tracking#Next.js Analytics#Session Recording#Session Replay#Conversion Funnels#Heatmaps#Feature Flags#Autocapture#User Journey#posthog tutorial#next.js analytics setup#session recording guide#conversion funnel analysis#user behavior tracking

Found this article helpful?

Share it with your network and help others learn too!

Mohammad Alhabil

Written by Mohammad Alhabil

Frontend Developer & Software Engineer passionate about building beautiful and functional web experiences. I write about React, Next.js, and modern web development.