Stickybeak Docs Dashboard Get early access

Frameworks

Gatsby

Gatsby analytics with Stickybeak starts by adding its script to your rendered pages; this guide shows you where it belongs and how to track page views, goals and purchase revenue. It is a lighter alternative to Google Analytics for Gatsby, with live visitors, goals and revenue attribution in one script.

Add the script

  1. Put your site ID in an environment variable

    Add it to .env.production (Gatsby reads this file for gatsby build) or to your host's build settings.

    GATSBY_STICKYBEAK_SITE_ID=YOUR_SITE_ID
  2. Add the tag in gatsby-ssr

    Create gatsby-ssr.tsx (or .jsx) at the root of your project, or add to the one you have:

    import * as React from "react";
    import type { GatsbySSR } from "gatsby";
    
    export const onRenderBody: GatsbySSR["onRenderBody"] = ({ setHeadComponents }) => {
      const siteId = process.env.GATSBY_STICKYBEAK_SITE_ID;
      if (process.env.NODE_ENV !== "production" || !siteId) return;
    
      setHeadComponents([
        <script
          key="stickybeak"
          defer
          data-site={siteId}
          data-domain="example.com"
          src="https://app.usestickybeak.com/_cfw/s.js"
        />,
      ]);
    };
  3. Build and deploy

    Run gatsby build and deploy. gatsby develop doesn't load the script.

Check it's working

Test the deployed site, then verify your install.

Track goals

Add data-goal to rendered links or buttons. For other events, use the typed queued helper below. See Custom goals.

<Link to="/pricing" data-goal="view_pricing" data-goal-from="hero">See pricing</Link>
type GoalProps = Record<string, string | number | boolean>;
type Stickybeak = ((goal: string, props?: GoalProps) => void) & { q?: unknown[][] };

declare global {
  interface Window {
    stickybeak?: Stickybeak;
  }
}

export function track(goal: string, props?: GoalProps): void {
  if (typeof window === "undefined") return; // on the server: nothing to do
  if (!window.stickybeak) {
    // Hold calls made before the script loads; it sends them when it arrives.
    const queue: Stickybeak = (...args) => {
      (queue.q ??= []).push(args);
    };
    window.stickybeak = queue;
  }
  window.stickybeak(goal, props);
}
import * as React from "react";
import { track } from "../lib/stickybeak";

export function DownloadButton({ file }: { file: string }) {
  return (
    <a href={`/downloads/${file}`} download onClick={() => track("download", { file })}>
      Download
    </a>
  );
}

Track purchases

After confirming an order in the browser, send:

window.stickybeak?.("purchase", { revenue: 49, currency: "USD", order_id: "ORDER_ID" });

Use real values; see Revenue.

Page changes

Links, navigate(), back and forward count new paths. Replace, query-only and hash-only changes do not. See Single-page apps.

If it isn't working

Check the production site ID and domain, then see Troubleshooting.