How To Use Fathom Analytics with Next.js

    In this guide, we'll walk through how to install Fathom Analytics in a Next.js project. Fathom is a simple and private website analytics platform—a great independent alternative to Google Analytics!

    1Create a new project

    If you are starting fresh, run the following command to create a new Next.js project. Otherwise, you can proceed with these steps to add Fathom to an existing Next.js app.

    npm create next-app my-website
    cd my-website

    2Install dependencies

    Install the fathom-client library, a thin wrapper around the Fathom tracking script designed for environments with client-side routing.

    npm install fathom-client

    Source on GitHub | npm package

    3Connect Fathom

    Create a pages/_app.js file like this and paste in your Fathom Site ID:

    import React, { useEffect } from 'react';
    import Router from 'next/router';
    import * as Fathom from 'fathom-client';
    // Record a pageview when route changes
    Router.events.on('routeChangeComplete', () => {
    Fathom.trackPageview();
    });
    function App({ Component, pageProps }) {
    // Initialize Fathom when the app loads
    useEffect(() => {
    if (process.env.NODE_ENV === 'production') {
    Fathom.load();
    Fathom.setSiteId('REPLACE_WITH_YOUR_SITE_ID');
    Fathom.trackPageview();
    }
    }, []);
    return <Component {...pageProps} />;
    }
    export default App;