DEV Community

Mario
Mario

Posted on • Originally published at mariokandut.com on

How to add Google analytics in Gatsby

Adding Google Analytics in Gatsby is quite easy and can be done in just a few minutes. There are two possible ways to add Google Analytics.

What you need first is a Google Analytics account. Start with setting up an account HERE.

1. Get your tracking ID from Google Analytics

After signing up for a Google Analytics account, create a property and get your tracking ID from the Tracking Code section under the Tracking Info menu. The tracking ID looks like this UA-12341234-1.

2. Add website tracking

Now you have two options:

In most cases the official plugin should be sufficient. Only if you have customized the html.js already, (script injection, etc.) you can add the tracking code there.

💰: Start your cloud journey with $100 in free credits with DigitalOcean!

Add Google Analytics via official plugin

Install the plugin.

npm install gatsby-plugin-google-gtag
Enter fullscreen mode Exit fullscreen mode

Add the plugin to your gatsby-config.js file:

module.exports = {
  plugins: [
    // All other plugins
    {
      resolve: `gatsby-plugin-google-gtag`,
      options: {
        // You can add multiple tracking ids and a pageview event will be fired for all of them.
        trackingIds: [
          'ADD-YOUR-TRACKING-CODE-HERE', // Google Analytics / GA
          // optional
          'OPTIONAL----AW-CONVERSION_ID', // Google Ads / Adwords / AW
          'OPTIONAL----DC-FLOODIGHT_ID', // Marketing Platform advertising products (Display & Video 360, Search Ads 360, and Campaign Manager)
        ],
        // This object gets passed directly to the gtag config command
        // This config will be shared across all trackingIds
        gtagConfig: {
          optimize_id: 'OPT_CONTAINER_ID',
          anonymize_ip: true,
          cookie_expires: 0,
        },
        // This object is used for configuration specific to this plugin
        pluginConfig: {
          // Puts tracking script in the head instead of the body
          head: false,
          // Setting this parameter is also optional
          respectDNT: true,
          // Avoids sending pageview hits from custom paths
          exclude: ['/preview/**', '/do-not-track/me/too/'],
        },
      },
    },
  ],
};
Enter fullscreen mode Exit fullscreen mode

All configuration options can be found in the plugin docs.

Add Google Analytics in html.js

If you have already a html.js file, skip the next paragraph.

Gatsby uses a React component to server render the <head> and other parts of the HTML outside of the core Gatsby application. Most sites should use the default html.js shipped with Gatsby and customizing html.js is not supported within a Gatsby Theme.

If you need to insert custom HTML into the <head> or <footer> of each page on your site, you can use html.js.

Copy the default html.js:

cp .cache/default-html.js src/html.js
Enter fullscreen mode Exit fullscreen mode

Then add the website tracking code from Google Analytics:

<script
  async
  src="https://www.googletagmanager.com/gtag/js?id=UA-12341234-1"
/>
<script
  dangerouslySetInnerHTML={{
    __html: `
    window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-12341234-1');
  `,
  }}
/>
Enter fullscreen mode Exit fullscreen mode

IMPORTANT: I recommend using an environment variable to store your GA_TRACKING_ID.

3. Build and Test.

The plugin only works in production mode. Hence, to test the correct firing of events run: gatsby build && gatsby serve. After deploying your website confirm that website tracking is working in Google Analytics.

🎉🎉🎉 Congratulations! You have successfully added Google Analytics to your website. 🎉🎉🎉

Thanks for reading and if you have any questions , use the comment function or send me a message @mariokandut.

If you want to know more about Gatsby, have a look at these Gatsby Tutorials.

References (and Big thanks):Gatsby Docs

Top comments (0)