DEV Community

Cover image for How to set up Fathom Analytics with Next.js app router
Sibiraj
Sibiraj

Posted on

How to set up Fathom Analytics with Next.js app router

This guide explains how to integrate Fathom Analytics with the new Next.js App Router. If you want to integrate Fathom Analytics with the Page Router, you can refer to the Vercel guide.

Create a Fathom Account

To get started with Fathom Analytics, you'll first need to create a Fathom account. If you haven't already, you can sign up for an account here. After signing up, make sure to add a website to your Fathom account to obtain the site ID you'll need for integration

Install fathom-client library

fathom-client is a javascript library for Fathom Analytics which offers asynchronous loading and importable functions

npm install fathom-client
Enter fullscreen mode Exit fullscreen mode

Add Fathom into Your Next.js App Router

Once you've installed fathom client and also assuming that you've setup nextjs app with app router.

// Fathom.tsx

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

export default function Fathom() {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    // Initialize Fathom when the app loads
    // Example: yourdomain.com
    //  - Do not include https://
    //  - This must be an exact match of your domain.
    //  - If you're using www. for your domain, make sure you include that here.
    load('YourSiteId', {
      includedDomains: ['yourDomain.com'],
      spa: 'auto',
      // skips automatically tracking page views on script load
      auto: false,
    });

    trackPageview();

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

  return null;
}
Enter fullscreen mode Exit fullscreen mode

Note the 'use client' directive at the beginning of the file. This directive is required for Next.js 13 since the useEffect hook is marked as a client-only hook.

Then you can import the file in your layout component

// app/layout.tsx

import './globals.css';
import { Inter } from 'next/font/google';
import { ReactNode } from 'react';

import Fathom from './Fathom';

const inter = Inter({
  subsets: ['latin'],
});

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang='en' className={inter.className}>
      <body>
        {children}
        <Fathom /> // add your component
      </body>
    </html>
  );
}
Enter fullscreen mode Exit fullscreen mode

That would be it, by following this you should be able to integrate Fathom with your Next.js application that uses the new app router.

Start tracking 👋

Top comments (0)