Using Fathom Analytics with Next.js

Fathom Analytics is a privacy-focused alternative to traditional analytics tools. This guide will show you how to integrate Fathom with your Next.js application.

First, install the Fathom client package:

npm install fathom-client

Create a new file called app/fathom.tsx in your project:

app/fathom.tsx
'use client';
import { load, trackPageview } from 'fathom-client';
import { useEffect, Suspense } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';
function TrackPageView() {
const pathname = usePathname();
const searchParams = useSearchParams();
useEffect(() => {
load(process.env.NEXT_PUBLIC_FATHOM_ID, {
auto: false
});
}, []);
useEffect(() => {
if (!pathname) return;
trackPageview({
url: pathname + searchParams?.toString(),
referrer: document.referrer
});
}, [pathname, searchParams]);
return null;
}
export function FathomAnalytics() {
return (
<Suspense fallback={null}>
<TrackPageView />
</Suspense>
);
}

This component does the following:

  1. Loads the Fathom script when the component mounts
  2. Tracks pageviews when the route changes

Note: Ensure you add your Fathom ID to your .env file.

Add the Fathom component to your root app/layout.tsx file:

app/layout.tsx
import { FathomAnalytics } from './fathom';
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>
<FathomAnalytics />
{children}
</body>
</html>
);
}
  1. The Fathom component is a client component (e.g. "use client")
  2. We use usePathname() and useSearchParams() to track route changes
  3. The Fathom script is loaded with auto: false to prevent automatic pageview tracking

To track custom events, you can use the trackEvent function from fathom-client:

import { trackEvent } from 'fathom-client';
// In your component
const handleClick = () => {
trackEvent('GOAL_ID', 0); // 0 is the value (optional)
};

Replace 'GOAL_ID' with the actual goal ID from your Fathom dashboard.

By following this guide, you'll have Fathom Analytics integrated into your Next.js application, providing privacy-focused analytics for your site.

Couldn't find the guide you need?