Gatsby: [gatsby-plugin-google-gtag] Analytics isn't working

Created on 31 Mar 2019  路  22Comments  路  Source: gatsbyjs/gatsby

Summary

Relevant information

With the default setting of gatsby-plugin-google-gtag, analytics doesn't seem to work at all.
No active users or custom events are being tracked.
I tested on production, also tried putting script into header

Environment (if relevant)

System:
OS: macOS High Sierra 10.13.6
CPU: x64 Intel(R) Core(TM) i7-7920HQ CPU @ 3.10GHz
Shell: 5.3 - /bin/zsh
Binaries:
Node: 10.10.0 - /usr/local/bin/node
npm: 6.4.1 - /usr/local/bin/npm
Browsers:
Chrome: 73.0.3683.86
Safari: 12.1
npmPackages:
gatsby: ^2.2.8 => 2.2.8
gatsby-image: ^2.0.34 => 2.0.34
gatsby-plugin-catch-links: ^2.0.13 => 2.0.13
gatsby-plugin-facebook-pixel: ^1.0.3 => 1.0.3
gatsby-plugin-google-analytics: ^2.0.17 => 2.0.17
gatsby-plugin-google-gtag: ^1.0.16 => 1.0.16
gatsby-plugin-react-helmet: ^3.0.10 => 3.0.10
gatsby-plugin-sharp: ^2.0.30 => 2.0.30
gatsby-remark-autolink-headers: ^2.0.16 => 2.0.16
gatsby-remark-copy-linked-files: ^2.0.11 => 2.0.11
gatsby-remark-images: ^3.0.10 => 3.0.10
gatsby-source-filesystem: ^2.0.28 => 2.0.28
gatsby-transformer-remark: ^2.3.8 => 2.3.8
gatsby-transformer-sharp: ^2.1.17 => 2.1.17
npmGlobalPackages:
gatsby-cli: 2.4.4

File contents (if changed)

gatsby-config.js:

module.exports = {
  siteMetadata: {
    title: `Gatsby Default Starter`,
  },
  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: [
          "<my_google_tracking_id>", // Google Analytics / GA
          // "AW-CONVERSION_ID", // Google Ads / Adwords / AW
          // "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 accross 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: true,
          // Setting this parameter is also optional
          respectDNT: true,
          // Avoids sending pageview hits from custom paths
          // exclude: ["/preview/**", "/do-not-track/me/too/"],
        },
      },
    },
    {
      resolve: `gatsby-plugin-react-helmet`
    },
    {
      resolve: 'gatsby-transformer-remark',
      options: {
        plugins: [
          {
            resolve: 'gatsby-remark-images',
            options: {
              maxWidth: 970,
            },
          },
          {
            resolve: "markdown-embed-youtube"
          },
          `gatsby-remark-autolink-headers`
        ],
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/src/pages/blog/posts`,
        name: "pages",
      },
    },
    {
      resolve: `gatsby-plugin-facebook-pixel`,
      options: {
        pixelId: '',
      },
    },
    `gatsby-remark-copy-linked-files`,
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-remark-images`,
      options: {
        maxWidth: 1080,
      },
    }
  ],
}
question or discussion

Most helpful comment

This plugin has issues. This is how I solved it:

Put it at very first position so it is the first plugin to be loaded.
Remove all optional attributes you don't need or are not sure about what they do.

This is how it looks in my gatsby-config.js:

  plugins: [
    {
      resolve: `gatsby-plugin-google-analytics`,
      options: {
        trackingId: "UA-1111111111-1",
        head: true,
        anonymize: true,
      },
    },
  // other plugins

All 22 comments

Problem was in optimize_id: "OPT_CONTAINER_ID",
Why is it in default documentation?

Problem was in optimize_id: "OPT_CONTAINER_ID",
Why is it in default documentation?

Can you elucidate on this?

@janbaykara, I got tripped up on this, too.

Basically, the "How to use" at https://www.gatsbyjs.org/packages/gatsby-plugin-google-gtag/ shows optimize_id: "OPT_CONTAINER_ID" which breaks analytics until it is removed.

I'm using this config:

{
      resolve: `gatsby-plugin-google-analytics`,
      options: {
        header: true,
        trackingId: process.env.GA_ID,
      },
    },

And it is not working for me. No data is displayed in GA.

Anyone found the solution?

I am doing gatsby build && gatbsy serve and tried even another plugin, but no success:

{
      resolve: `gatsby-plugin-gtag`,
        options: {
          // your google analytics tracking id
          trackingId: `XXXX`,
          // Puts tracking script in the head instead of the body
          head: true,
          // enable ip anonymization
          anonymize: true,
        },
    });
  }

Anyone found the solution?

I am doing gatsby build && gatbsy serve and tried even another plugin, but no success:

{
      resolve: `gatsby-plugin-gtag`,
        options: {
          // your google analytics tracking id
          trackingId: `XXXX`,
          // Puts tracking script in the head instead of the body
          head: true,
          // enable ip anonymization
          anonymize: true,
        },
    });
  }

I figured out!

It was the path of the .env file inside the gatsby-config.js of the starter that I am using:

require('dotenv').config({ path:.env, });

Anyone found the solution?
I am doing gatsby build && gatbsy serve and tried even another plugin, but no success:

{
      resolve: `gatsby-plugin-gtag`,
        options: {
          // your google analytics tracking id
          trackingId: `XXXX`,
          // Puts tracking script in the head instead of the body
          head: true,
          // enable ip anonymization
          anonymize: true,
        },
    });
  }

I figured out!

It was the path of the .env file inside the gatsby-config.js of the starter that I am using:

require('dotenv').config({ path:.env, });

Actually it was not that, I even removed again the { path:.env, }.
So I kept

require('dotenv').config(); const { ACCESS_TOKEN, SPACE_ID, ANALYTICS_ID } = process.env;

then, in the .env file i inserted the credentials like: ACCESS_TOKEN='mytoken' etc

How the .env is a .gitignore file, in Netlify I used the credentials inside the Build command like:

SPACE_ID='xxxxx' ACCESS_TOKEN='xxxxx' ANALYTICS_ID='xxxxxx' gatsby build

It worked! clap

I don't know why but I just put the plugin as the first one in the config file.

This plugin has issues. This is how I solved it:

Put it at very first position so it is the first plugin to be loaded.
Remove all optional attributes you don't need or are not sure about what they do.

This is how it looks in my gatsby-config.js:

  plugins: [
    {
      resolve: `gatsby-plugin-google-analytics`,
      options: {
        trackingId: "UA-1111111111-1",
        head: true,
        anonymize: true,
      },
    },
  // other plugins

If you have problems, keep in mind "do not track" setting in your browser.
Basically for me having this setting enabled in plugin was breaking tracking no matter what browser setting was. Maybe it's broken in the plugin or analytics itself?

Anyways, tracking seems to work now, but it's quite unstable. Not all events are tracked so not sure what's the problem.
Anybody else has that?

This plugin has issues. This is how I solved it:

Put it at very first position so it is the first plugin to be loaded.
Remove all optional attributes you don't need or are not sure about what they do.

This is how it looks in my gatsby-config.js:

  plugins: [
    {
      resolve: `gatsby-plugin-google-analytics`,
      options: {
        trackingId: "UA-1111111111-1",
        head: true,
        anonymize: true,
      },
    },
  // other plugins

I would just like to add (for future note) that moving gatsby-plugin-google-analytics to the top of my plugins solved the issue. Thanks for the assist @ThomasUta !

This thing hasn't worked me since the first time I tried (maybe 1.5 years ago). At one point it did track the first pageview, but the subsequent navigations to other pages didn't trigger anything. Quite unsatisfied with the quality of this library and has caused me to waste a lot of time. You would think that given that this is an officially supported plugin it would have official-level support. It's not nice having to debug 3rd party code with no obvious clues why it's not working. Even tricks like the aforementioned moving of the plugin to the top of the plugin list are ugly hacks, not permanent fixes.

Sometimes I feel Gatsby has become too tangled of a mess to use it without weird problems. Or well, it was a mess to start with and it feels it still is. It's just as a developer I don't have interest in debugging arcane problems. And the JS source code itself looks quite spagetti. No wonder no one can understand what is the problem with it.

@TeemuKoivisto
Well, everything is opensource and pluggable, so you can always write your own analytics wrapper and not rely on someone else's ugly hacks. You would have to do it manually anyways if you go to the plain react app without gatsby.

@AAverin I am not sure what you were going for, yes I can write my own wrapper? But why should I? I thought the point of having libraries is that I can rely on them to let me focus on more productive things. And "go to the plain react app", what you mean by that? I am not making a plain react app, that is why I am here. I just wanted to add GA with basic pageviews and that's it. Didn't think it was this hard.

After fiddling with the gatsby-browser.js and gatsby-ssr.js for some time I got the thing working. Didn't first understand what that gtag is for, but it seems Google is advocating people to use it instead of analytics.js.

So I decided to give gatsby-plugin-google-gtag library a try and it seems it worked straight away. I don't know what is different in the gatsby-plugin-google-analytics code, but for some reason it didn't work as intended for me with pageviews. No need to move the plugin to the top of the plugin list. I hope it's now resolved and I don't have to think about it anymore.

Thank you for opening this!

The PR (https://github.com/gatsbyjs/gatsby/pull/19175) addressed some of the things here although I never had any issues with the positioning of the analytics plugin in the plugins list. But it's now in the docs, it doesn't hurt anyone...

This could also be an issue with a bunch different outside factors like browser settings, AdBlockers, software on your machine. Or even how Google handles gtag and analytics differently. AFAIK they're pushing people towards gtag, so feel free to look into that.

We're marking this issue as answered and closing it for now but please feel free to comment here if you would like to continue this discussion. We also recommend heading over to our communities if you have questions that are not bug reports or feature requests. We hope we managed to help and thank you for using Gatsby!

Quite silly to say this, but I noticed that the it is disabled gatsby develop. Could see GA is working after running gatsby build and gatsby serve and opening the localhost.

Nothing was added or altered other than adding below in gatsby-config.js.

plugins: [
    {
      resolve: `gatsby-plugin-google-analytics`,
      options: {
        // replace "UA-XXXXXXXXX-X" with your own Tracking ID
        trackingId: "UA-XXXXXXXXX-X",
        head: false,
        anonymize: true
      },
    },
   ...
]

Moving the plugin to the top did nothing for me, but switching to gatsby-plugin-gtag and making sure it is right below gatsby-plugin-react-helmet in gatsby-config.js did! The options are basically the same as with google-analytics:

  plugins: [
    `gatsby-plugin-react-helmet`,
    {
      resolve: `gatsby-plugin-gtag`,
      options: {
        trackingId: `UA-XXXXXXXXX-X`,
        head: false,
        anonymize: true,
      },
    },
   ...
  ],

@ilyankou are you able to get it to track page views? it seems to be hard-coded not to do so.

@ardalis Yes, gtag works for it all (I created the code snippet from Google Analytics): https://developers.google.com/analytics/devguides/collection/gtagjs/

See what Google Tag Assistant shows (I only added the gtag plugin).

Screenshot 2020-06-06 at 15 00 03

Did this go anywhere? I'd love to get GA working in dev/test mode, so we can build and test analytics (we have separate dev and prod GA profiles)

after configuring how to how acces gatg and fbq in the project in order to emit events like fbq('init', '1234567'); fbq('track', 'PageView'); like this and fbq('track', 'checkout'); in a particular pages like this

I tried a variety of options listed above and this is the combo that eventually worked for me:

plugins: [
    { // this must be loaded first in order to work
      resolve: `gatsby-plugin-gtag`, // note this instead of gatsby-plugin-react-helmet
      options: {
        trackingId: "UA-XXXXXXXXX-X",
        head: true, // note this is TRUE and not FALSE as listed in other examples above
        anonymize: true
      }
    },
    "gatsby-plugin-react-helmet",
    // other plugins
  ]
Was this page helpful?
0 / 5 - 0 ratings

Related issues

kalinchernev picture kalinchernev  路  3Comments

ghost picture ghost  路  3Comments

signalwerk picture signalwerk  路  3Comments

hobochild picture hobochild  路  3Comments

brandonmp picture brandonmp  路  3Comments