How to Add Fathom Analytics in Next.js App Router

In case you haven't heard about Fathom Analytics, it is a tool to understand how many people visit your website and what they do there.

It's different from other similar tools (like Google Analytics) because it cares a lot about privacy.

This means it doesn't collect personal details about your visitors, making it a good choice for people who want to protect their visitors' privacy.

People choose Fathom because it's easy to use, doesn't slow down your website, and helps you follow privacy laws without needing complicated setups or giving up useful information about your website's traffic.

This article will look at how you can add Fathom Analytics to your Next.js application.

Get Started

Note: This article assumes you have an existing Next.js application and are using 13+.

You'll also need a Fathom account.

You can sign up for an account here, and once it's done, you'll get a unique code. Keep it handy, as you'll need it for the setup in your Next.js app.

1) Install Fathom Client

The only thing you'll need to install is the fathom-client library:

npm install fathom-client

2) Set up Fathom in Your App

I've added comments to explain the code so please read them but for copy/paste-ability, I've added a large code block.

Create a file called Fathom.tsx (or .jsx if you use JS).

Then paste in the following:

'use client'; // 👈 Don't forget your client directive

import { load, trackPageview } from 'fathom-client';
import { useEffect, Suspense } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';

function TrackPageView() {
  // Current Path
  const pathname = usePathname();
  // Current query params
  const searchParams = useSearchParams();

  // Load the Fathom script on mount
  useEffect(() => {
    // Optional: Only track on production; remove these two lines if you want to track other environments
    const env = process.env.NODE_ENV;
    if (env !== "production") return;

    load('MY_FATHOM_ID', {
      auto: false,
      // Optional but I like to explicitly choose the domains to track:
      includedDomains: ["www.yourdomain.com", "yourdomain.com"],
    });
  }, []);

  // Record a pageview when route changes
  useEffect(() => {
    if (!pathname) return;

    trackPageview({
      url: pathname + searchParams.toString(),
      referrer: document.referrer
    });
  }, [pathname, searchParams]); // 👈 Track page views if path or params change

  return null;
}

// We use this in our main layout.tsx or jsx file
export default function Fathom() {
  return (
    <Suspense fallback={null}>
      <TrackPageView />
    </Suspense>
  );
}

Then you need to include this in your main layout.tsx (or layout.jsx) file:

import Fathom from './Fathom';

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <head></head>
      <body>
        <Fathom />
        <Page>{children}</Page>
      </body>
    </html>
  );
}

3) Deploy

Now, all you need to do is deploy your changes!

Fathom will now track visits to your site.

Note if you are having issues: If you don't see traffic in your Fathom Dashboard, make sure you have the exact domain in your includedDomains array. This is something that caught me. 😅 Or remove the includedDomains altogether until you confirm it's setup correctly.


And there you go!

You've added Fathom Analytics to your Next.js app.

This setup allows you to monitor site traffic while maintaining user privacy. Keep your tools updated for any new Fathom and Next.js features or changes.

If you want to see how we do it on Codú, you can see the working code here.

Happy coding! 🍕

AnalyticsNextjs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.