# Using Fathom Analytics with Next.js

**Author:** Lee Robinson

---

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.

## Step 1: Install Fathom Client

First, install the Fathom client package:

`npm install fathom-client`

## Step 2: Create a Fathom Client Component

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

`'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. ## Step 3: Add Fathom Component to Root Layout Add the Fathom component to your root `app/layout.tsx` file: `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     ## Custom Events To track custom events, you can use the `trackEvent` [function](https://github.com/derrickreimer/fathom-client) 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.

---

[View full KB sitemap](/kb/sitemap.md)
