Next.js
Fathom Analytics works well with Next.js with minimal configuration. A huge thank you to Derrick Reimer, founder of SavvyCal for creating the incredible fathom-client package.
If you're using Next.js App Router (v13.4+)
The App Router is the recommended approach for new Next.js applications. Here's how to set up Fathom:
- Install the fathom-client package:
npm install fathom-client- Create a Fathom component to load the tracking script. Create a new file at
app/components/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('YOUR-SITE-ID', { auto: false }); }, []); useEffect(() => { if (!pathname) return; trackPageview({ url: pathname + searchParams?.toString(), referrer: document.referrer }); }, [pathname, searchParams]); return null;} export default function Fathom() { return ( <Suspense fallback={null}> <TrackPageView /> </Suspense> );}- Import and use the Fathom component in your root layout (
app/layout.tsx):
import Fathom from './components/Fathom'; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <Fathom /> {children} </body> </html> );}For more details, see the fathom-client App Router documentation.
If you're using Next.js Pages Router
If you're using the Pages Router (Next.js 12 or the pages/ directory in newer versions):
Please see the fathom-client Pages Router documentation.
Tracking events
To track custom events, you can use the trackEvent function from fathom-client:
import { trackEvent } from 'fathom-client'; // Track a simple eventtrackEvent('Button Clicked'); // Track an event with a value (in cents for monetary values)trackEvent('Purchase Completed', { _value: 9900 });Further customization
To learn about all the options we offer, read our advanced documentation here.