โ€” Mar 15, 2023 ยท 2 Min read

Give this post a share? ๐Ÿ™

How to setup Fathom Analytics with Next.js 13 App Directory

If you're an early adopter of the Next.js app directory, this is my solution for integrating Fathom analytics with the Next.js 13 app directory.

What's the problem?

The new app directory for Next.js on longer exposes the router.events.on('routeChangeComplete'), which was the defacto way to integrate Fathom, Google Analytics, and tracking pageviews in general.

Solution

The maintainers of Next.js have recommended the following solution, which I'm sure will show up in the docs at some point. For now, hopefully this blog post helps you find it quicker!

Create a client component file called Fathom.tsx:

// 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("MY_FATHOM_ID", {
      includedDomains: ["yourwebsite.com"],
    });
  }, []);

  useEffect(() => {
    trackPageview();

    // Record a pageview when route changes
  }, [pathname, searchParams]);

  return null;
}

export default function Fathom() {
  return (
    <Suspense fallback={null}>
      <TrackPageView />
    </Suspense>
  );
}

And then drop that into your root layout:

// src/app/layout.tsx

export default function RootLayout({ children }: PropsWithChildren) {
  return (
    <html lang="en">
      <body>
        {children}

        {/* ALL SET UP! */}
        <Fathom />
      </body>
    </html>
  );
}

Like I said, this solution will likely be outdated soon, but hopefully it helps a few of you during this interim period! I will try to post the "official" solution later.