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

Last updated Mar 15, 2023
written byZach

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'routeChangeComplete'), which was the defacto way to integrate Fathom, Google Analytics, and tracking pageviews in general.


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: [""],
  }, []);

  useEffect(() => {

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

  return null;

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

And then drop that into your root layout:

// src/app/layout.tsx

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

        {/* ALL SET UP! */}
        <Fathom />

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.