Fathom Analytics Fathom Analytics

How to use Fathom Analytics with Next.js

Fathom Analytics works well with Next.js with minimal configuration. A huge thank you to Derrick Reimer, founder of StaticKit for his help with this. He was responsible for writing the original plugin for Next.js. We've now made some changes to our code, and can give some simple instructions for you to follow:

  1. Create a new file called _app.js in your pages directory
  2. Add the code below to the file (remember to add your own Site ID and custom domain, if you have one)
import React, { useEffect } from 'react';
import Router from 'next/router';

function App({ Component, pageProps }) {
    // Initialize Fathom when the app loads
    useEffect(() => {
        let tracker = window.document.createElement('script');
        let firstScript = window.document.getElementsByTagName('script')[0];
        tracker.defer = true;
        tracker.setAttribute('site', 'ABCDEFG');
        tracker.setAttribute('spa', 'auto');
        tracker.src = 'https://cdn.usefathom.com/script.js';
        firstScript.parentNode.insertBefore(tracker, firstScript);
    }, []);
    return <Component {...pageProps} />;}
export default App;

Then you can recompile, and you're ready to roll.

Further customization

To learn about all the options we offer, read our advanced documentation here.