Adding analytics to Gatsby web apps

Once you have added your website to Panelbear, all that is left to do is integrate our analytics snippet.

It's a small piece of code that runs on your website, and it collects the metrics necessary to show you the insights in the dashboard. For more information on what it collects check out What do we collect?.

Steps

To install Panelbear on your Gatsby project all you have to do is to tell Gatsby to inject the analytics snippet into the rendered HTML document.

  1. Create a file called gatsby-ssr.js on your project's root directory.
  2. Paste the following snippet and replace YOUR_SITE_ID with your Panelbear's Site ID.
import React from "react";

const PANELBEAR_SITE_ID = "YOUR_SITE_ID";

const PANELBEAR_CONFIG = {
  site: PANELBEAR_SITE_ID,
  spaMode: "history",
  debug: false,
};

export const onRenderBody = ({ setPostBodyComponents }) => {
  setPostBodyComponents([
    <script
      key="panelbear-analytics-src"
      async
      src={`https://cdn.panelbear.com/analytics.js?site=${PANELBEAR_SITE_ID}`}
    />,
    <script
      key="panelbear-analytics-code"
      dangerouslySetInnerHTML={{
        __html: `
          window.panelbear = window.panelbear || function() { (window.panelbear.q = window.panelbear.q || []).push(arguments); };
          panelbear('config', ${JSON.stringify(PANELBEAR_CONFIG)});
        `,
      }}
    />,
  ]);
};

You can optionally set debug: true to see logs on your browser's console when developing on localhost.

Please note Gatsby will not auto-reload this file during development, you may need to restart the server between changes.

For more information on how this method works, you can check out Gatsby's documentation on SSR APIs.

Check your installation

After you have added our analytics script to the HTML of your website, you should be able to see pageviews show up in the dashboard within a minute of the visitors coming into your website.

If you need help, you can reach out to us at [email protected].

Tip: Check out our local development guide for some tips and tricks when testing Panelbear on your machine.