Support home / Integrations

Astro

Fathom Analytics works great with Astro. Since Astro generates static sites by default (with optional server-side rendering), adding Fathom is straightforward.

Adding the Fathom script

The simplest way to add Fathom to your Astro site is to include the script in your base layout. Open your layout file (commonly src/layouts/Layout.astro or src/layouts/BaseLayout.astro) and add the Fathom script just before the closing </head> tag:

<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.

If you’re using View Transitions

Astro’s View Transitions feature enables smooth page transitions without full page reloads. If you’re using this feature, you’ll need to enable SPA mode on your Fathom script:

<script src="https://cdn.usefathom.com/script.js" data-site="YOUR-SITE-ID" data-spa="auto" defer></script>

Using the astro-fathom component

There’s also a community-built astro-fathom package, maintained by Astro core maintainer Tony Sullivan, that provides a <Fathom> component. It exposes all of our advanced tracking options as component props and stubs out a console logger during development for easy debugging.

  1. Install the package:
npm install astro-fathom
  1. Import the <Fathom> component into your layout and add it inside the <head>:
---
import { Fathom } from 'astro-fathom';
---

<html>
  <head>
    <!-- other head tags -->
    <Fathom site="YOUR-SITE-ID" />
  </head>
</html>

Alternatively, set a FATHOM_SITE environment variable and render <Fathom /> with no props.

By default, the tracking script is only included in production builds. When you run astro dev, window.fathom is replaced with a logger that prints tracking events to the browser console, so you can debug without sending any data. The component also accepts props for advanced options such as spa, honorDnt, auto, and canonical.

Note: This is a community package and is not maintained by Fathom.

Tracking events

To track custom events, you can use inline scripts on specific pages or components:

<button id="signup-button">Sign Up</button>

<script>
  document.getElementById('signup-button').addEventListener('click', () => {
    fathom.trackEvent('Signup Button Clicked');
  });
</script>

Further customization

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