OnyxMetric
Integration GuidesReact

Gatsby

Step-by-step guide to add OnyxMetric cookieless analytics to your Gatsby site and start tracking visitors

Gatsby generates each page's <head> at build time. Register the script through onRenderBody in gatsby-ssr.js, or use Gatsby's <Script> component if you want to pick the load strategy.

Copy your tracking snippet

In OnyxMetric, open your site's Site Settings and copy the tracking script. It looks like this:

<script src="https://app.onyxmetric.com/api/script.js?siteId=YOUR_SITE_ID" async></script>

YOUR_SITE_ID is the numeric ID of your site.

Add the snippet to Gatsby

Create gatsby-ssr.js in the project root if it does not exist, and register the script with setHeadComponents:

gatsby-ssr.js
import React from "react";

export const onRenderBody = ({ setHeadComponents }) => {
  setHeadComponents([
    <script
      key="onyxmetric-analytics"
      src="https://app.onyxmetric.com/api/script.js?siteId=YOUR_SITE_ID"
      async
    />,
  ]);
};

Every generated page gets the tag in its <head>.

The Gatsby Script API loads third-party scripts with a strategy of post-hydrate, idle, or off-main-thread. Render it in a layout used by every page:

src/components/layout.js
import { Script } from "gatsby";

export default function Layout({ children }) {
  return (
    <>
      {children}
      <Script
        src="https://app.onyxmetric.com/api/script.js?siteId=YOUR_SITE_ID"
        strategy="post-hydrate"
      />
    </>
  );
}

Run gatsby build and deploy the public folder. Navigation through Gatsby's <Link> is tracked as pageviews automatically.

Check that it works

Load your live site and click through a few pages. Pageviews show up in the OnyxMetric dashboard within seconds.

If nothing arrives:

  • View the page source and search for script.js?siteId= to confirm the tag is present.
  • In the browser's Network tab, check that script.js returns 200 and that requests go to /api/track.
  • Turn off ad blockers, or proxy the script through your own domain.
  • Read script troubleshooting for other causes.

Track custom events

Gatsby renders components on the server during the build, so guard the call.

src/components/TrackedButton.js
export default function TrackedButton({ label, eventName, eventData }) {
  const handleClick = () => {
    if (typeof window !== "undefined") {
      window.onyx?.event(eventName, eventData);
    }
  };

  return <button onClick={handleClick}>{label}</button>;
}

Troubleshooting

  • Missing pageviews after client navigation: rare. If it happens, export onRouteUpdate from gatsby-browser.js and call window.onyx.pageview() when location.pathname changes, after testing the default.

Next steps

On this page