gatsbyjs / gatsby

The best React-based framework with performance, scalability and security built in.
https://www.gatsbyjs.com
MIT License
55.2k stars 10.33k forks source link

[gatsby-plugin-google-gtag] Analytics isn't working #12967

Closed AAverin closed 4 years ago

AAverin commented 5 years ago

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,
      },
    }
  ],
}
AAverin commented 5 years ago

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

janbaykara commented 5 years ago

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

Can you elucidate on this?

semireg commented 5 years ago

@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.

BrunoQuaresma commented 5 years ago

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.

Sarah86 commented 5 years ago

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,
        },
    });
  }
Sarah86 commented 5 years ago

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, });

Sarah86 commented 5 years ago

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

BrunoQuaresma commented 5 years ago

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

ThomasJanUta commented 4 years ago

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
AAverin commented 4 years ago

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?

srepollock commented 4 years ago

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 !

TeemuKoivisto commented 4 years ago

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.

AAverin commented 4 years ago

@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.

TeemuKoivisto commented 4 years ago

@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.

LekoArts commented 4 years ago

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!

jyoo commented 4 years ago

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
      },
    },
   ...
]
ilyankou commented 4 years ago

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,
      },
    },
   ...
  ],
ardalis commented 4 years ago

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

ilyankou commented 4 years ago

@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

alexblack commented 4 years ago

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)

sarathAvantari commented 3 years ago

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

dkoloditch commented 3 years ago

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
  ]
erichfw commented 3 years ago

I've been struggling with this for a while. I could get it working with by placing the gtag plugin before the other plugins (including the react helmet) as mentioned by @dkoloditch here. A mentioned already use gatsby build and gatsby serve as opposed to gatsby develop to test this. Also, for clarity, I am only running the gtag plugin. Some users above seem to be running the legacy analytics plugin also.

naojamg commented 3 years ago

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
  ]

this save my life

knambiar commented 3 years ago

Using the gatsby-plugin-google-gtag plugin worked for me, I had to set "send_page_view: true" in the options, it seems to default to false.

  {
      resolve: `gatsby-plugin-google-gtag`,
      options: {
        // You can add multiple tracking ids and a pageview event will be fired for all of them.
        trackingIds: [
          "<TRACKING ID GOES HERE>", // Google Analytics / GA
        ],
        // This object gets passed directly to the gtag config command
        // This config will be shared across all trackingIds
        gtagConfig: {
          anonymize_ip: true,
          cookie_expires: 0,
          send_page_view: true // default appears to be false.
        },
        // 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/"],
        },
      },
    },`
aaronamm commented 3 years ago

@knambiar Thank you for your solution. However, I don't quite understand how you can override send_page_view to true value. Here is the source code, https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-plugin-google-gtag/src/gatsby-ssr.js#L25

  const gtagConfig = pluginOptions.gtagConfig || {}
  const pluginConfig = pluginOptions.pluginConfig || {}

  // Prevent duplicate or excluded pageview events being emitted on initial load of page by the `config` command
  // https://developers.google.com/analytics/devguides/collection/gtagjs/#disable_pageview_tracking
  gtagConfig.send_page_view = false

As you can see, it looks like it always set to false. Even though we set it to true from gtagConfig in gatsby-config.js file.

In addition, I think we also need to update a setting in Google Analytics admin as in this video. https://www.youtube.com/watch?v=kO_GMfC1LHA&t=287s

FYI 9842 PR set send_page_view to false.

itstyro commented 2 years ago

did anyone found a reliable way to make it work? The gtag plugin isn't sending page view events to google tag manager. I have tried everything that is mentioned above in this thread

unimprobable commented 2 years ago

@itstyro Have you tried the GA Debug extension? This works pretty good to show what the scripts are doing. You might be able to step through in the console and get some insight to your issue.

ZiggStardust commented 2 years ago

https://github.com/gatsbyjs/gatsby/issues/12967#issuecomment-778745329

Worked for me :)

masafumimori commented 9 months ago

For someone who is still struggling with this issue (like me). The settings below worked for me. Hope this helps!

{
    resolve: `gatsby-plugin-google-gtag`,
    options: {
        trackingIds: [
            "G-XXXXXXX", // Google Analytics / GA
        ],
        pluginConfig: {
            head: true,
        },
    },
},