Adam Richardson

Add Fathom analtics to Next.js website

Adam Richardson /

/hooks/useFathom.js
import * as Fathom from "fathom-client";
import { useRouter } from "next/router";
import { useEffect } from "react";

export const useFathom = () => {
  const router = useRouter();

  useEffect(() => {
    if (process.env.NODE_ENV === "production") {
      Fathom.load(process.env.NEXT_PUBLIC_FATHOM_ID, {
        includedDomains: ["adamrichardson.dev"],
      });
    }

    function onRouteChangeComplete() {
      Fathom.trackPageview();
    }

    router.events.on("routeChangeComplete", onRouteChangeComplete);

    return () => {
      router.events.off("routeChangeComplete", onRouteChangeComplete);
    };
  }, [router.events]);
};

/pages/_app.js
import { useFathom } from "../hooks/useFathom";

function MyApp({ Component, pageProps }) {
  useFathom();
  return (
      <Component {...pageProps} />
  );
}

export default MyApp;

© 2021 Adam Richardson. All rights reserved.