React
Fathom Analytics works great with React applications. Whether you're using Create React App, Vite, or another React setup, the integration is straightforward.
Note: If you're using a React framework like Next.js, Remix, or Gatsby, check out our dedicated integration guides for those instead.
Simple setup (static sites)
If your React app doesn't use client-side routing (e.g., React Router), you can simply add the Fathom script to your index.html file:
<script src="https://cdn.usefathom.com/script.js" data-site="YOUR-SITE-ID" defer></script>Note: Replace `YOUR-SITE-ID` with your actual Fathom site ID. You can find this in your Fathom site settings.
With React Router (SPA)
If you're using React Router or similar client-side routing, you'll want to use the fathom-client package for proper page view tracking:
- Install fathom-client:
npm install fathom-client- Create a Fathom component that tracks page views on route changes:
// src/components/Fathom.tsximport { useEffect } from 'react';import { useLocation } from 'react-router-dom';import * as Fathom from 'fathom-client'; export function FathomAnalytics() { const location = useLocation(); useEffect(() => { Fathom.load('YOUR-SITE-ID', { auto: false }); }, []); useEffect(() => { Fathom.trackPageview(); }, [location.pathname, location.search]); return null;}- Add the component to your app, inside your Router:
// src/App.tsximport { BrowserRouter, Routes, Route } from 'react-router-dom';import { FathomAnalytics } from './components/Fathom'; function App() { return ( <BrowserRouter> <FathomAnalytics /> <Routes> {/* Your routes here */} </Routes> </BrowserRouter> );}Using the data-spa attribute
Alternatively, if you don't need programmatic control, you can add the script to your index.html with the data-spa attribute:
<script src="https://cdn.usefathom.com/script.js" data-site="YOUR-SITE-ID" data-spa="auto" defer></script>This tells Fathom to automatically detect and track client-side navigation.
Tracking events
To track custom events, use the trackEvent function from fathom-client:
import { trackEvent } from 'fathom-client'; function SignupButton() { const handleClick = () => { trackEvent('Signup Button Clicked'); // ... rest of your click handler }; return <button onClick={handleClick}>Sign Up</button>;}For events with monetary values (in cents):
trackEvent('Purchase Completed', { _value: 9900 }); // $99.00Environment variables
For better flexibility, store your site ID in an environment variable:
// ViteFathom.load(import.meta.env.VITE_FATHOM_SITE_ID); // Create React AppFathom.load(process.env.REACT_APP_FATHOM_SITE_ID);Further customization
To learn about all the options we offer, read our advanced documentation here.