Skip to content

Commit 1e8f665

Browse files
valsepieh
authored andcommitted
fix(gatsby-plugin-google-gtag): disable default pageview tracking (#9842)
The default behavior of the `config` snippet is to send a pageview automatically; this is in contrast with the `exclude` option and the plugin tracks, on page load, even the excluded pages. This PR solve also the double pageview hits on page load too: the first is made by the default behavior and the second one by the `onRouteUpdate` event.
1 parent a441468 commit 1e8f665

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

packages/gatsby-plugin-google-gtag/src/gatsby-ssr.js

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,13 @@ exports.onRenderBody = (
77
) => {
88
if (process.env.NODE_ENV !== `production`) return null
99

10+
const gtagConfig = pluginOptions.gtagConfig || {}
11+
12+
// Prevent duplicate or excluded pageview events being emitted on initial load of page by the `config` command
13+
// https://developers.google.com/analytics/devguides/collection/gtagjs/#disable_pageview_tracking
14+
15+
gtagConfig.send_page_view = false
16+
1017
const firstTrackingId =
1118
pluginOptions.trackingIds && pluginOptions.trackingIds.length
1219
? pluginOptions.trackingIds[0]
@@ -31,8 +38,8 @@ exports.onRenderBody = (
3138
: ``
3239
}
3340
${
34-
typeof pluginOptions.gtagConfig.anonymize_ip !== `undefined` &&
35-
pluginOptions.gtagConfig.anonymize_ip === true
41+
typeof gtagConfig.anonymize_ip !== `undefined` &&
42+
gtagConfig.anonymize_ip === true
3643
? `function gaOptout(){document.cookie=disableStr+'=true; expires=Thu, 31 Dec 2099 23:59:59 UTC;path=/',window[disableStr]=!0}var gaProperty='${firstTrackingId}',disableStr='ga-disable-'+gaProperty;document.cookie.indexOf(disableStr+'=true')>-1&&(window[disableStr]=!0);`
3744
: ``
3845
}
@@ -49,9 +56,7 @@ exports.onRenderBody = (
4956
${pluginOptions.trackingIds
5057
.map(
5158
trackingId =>
52-
`gtag('config', '${trackingId}', ${JSON.stringify(
53-
pluginOptions.gtagConfig || {}
54-
)});`
59+
`gtag('config', '${trackingId}', ${JSON.stringify(gtagConfig)});`
5560
)
5661
.join(``)}
5762
}

0 commit comments

Comments
 (0)