Add Fathom analytics to a Next.js website
Code for adding Fathom to Next.js website
This post is for showing how to add Fathom analytics to a Next.js website using the fathom-client package
Table of contents
Create hook
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]);
};
Use the hook within _app.js
import { useFathom } from "../hooks/useFathom";
function MyApp({ Component, pageProps }) {
useFathom();
return <Component {...pageProps} />;
}
export default MyApp;