Blog>
Snippets

Client-Side Route Change Tracking in Next.js

Capture client-side route changes in Next.js 14 to log page navigation events to an analytics platform like Mixpanel.
import { useEffect } from 'react';
import { useRouter } from 'next/router';
import mixpanel from 'mixpanel-browser';

export default function useRouteChangeTracker() {
  const router = useRouter();

  useEffect(() => {
    const handleRouteChange = (url) => {
      // Mixpanel tracking for page view
      mixpanel.track('Page Viewed', { page: url });
    };

    // Subscribe to route changes
    router.events.on('routeChangeComplete', handleRouteChange);

    // Unsubscribe from route changes on cleanup
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange);
    };
  }, [router.events]);
}
This code snippet defines a custom hook called `useRouteChangeTracker` that uses Next.js's Router events to track page views on client-side route changes. When the route changes (routeChangeComplete event), the `handleRouteChange` function is called, which logs the event to Mixpanel with the new url. The hook sets up the event listener on mount and removes it on unmount to prevent memory leaks.