place gtag event snippet head Gatsby/React site

Viewed 1152

I am having issues placing an event snippet in on my thank you-page. The site is built in GatsbyJS. My thought was placing the event snippet in using React helmet but can't seem to figure out how to do it correctly. I've tried all different things but neither seems to work:

<Helmet>
<script>
  gtag('event', 'conversion', {'send_to': 'AW-MYID'});
</script>
</Helmet>
<Helmet>
<script
  gtag('event', 'conversion', {'send_to': 'AW-MYID'});
/>
</Helmet>
<Helmet>
<script>
{`
  gtag('event', 'conversion', {'send_to': 'AW-MYID'});
`}
</script>
</Helmet>
1 Answers

According to gatsby-plugin-google-gtag documentation to add custom events in server-side rendering (SSR):

typeof window !== "undefined" && window.gtag("event", "click", { ...data })

You need to access to window object first. Of course, after checking if it's available the request time as the debugging HTML in Gatsby shows.

Of course, this assumes that you have properly installed the plugin in your gatsby-config.js. Ideal customization should look like:

  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: [
          "GA-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 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/"],
        },
      },
    },
  ],
Related