-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
gatsby-ssr.js
86 lines (75 loc) · 2.64 KB
/
gatsby-ssr.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import React from "react"
import { Minimatch } from "minimatch"
exports.onRenderBody = (
{ setHeadComponents, setPostBodyComponents },
pluginOptions
) => {
if (process.env.NODE_ENV !== `production` && process.env.NODE_ENV !== `test`)
return null
// Lighthouse recommends pre-connecting to google analytics
setHeadComponents([
<link
rel="preconnect dns-prefetch"
key="preconnect-google-analytics"
href="https://www.google-analytics.com"
/>,
])
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
const firstTrackingId =
pluginOptions.trackingIds && pluginOptions.trackingIds.length
? pluginOptions.trackingIds[0]
: ``
const excludeGtagPaths = []
if (typeof pluginConfig.exclude !== `undefined`) {
pluginConfig.exclude.map(exclude => {
const mm = new Minimatch(exclude)
excludeGtagPaths.push(mm.makeRe())
})
}
const setComponents = pluginConfig.head
? setHeadComponents
: setPostBodyComponents
const renderHtml = () => `
${
excludeGtagPaths.length
? `window.excludeGtagPaths=[${excludeGtagPaths.join(`,`)}];`
: ``
}
${
typeof gtagConfig.anonymize_ip !== `undefined` &&
gtagConfig.anonymize_ip === true
? `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);`
: ``
}
if(${
pluginConfig.respectDNT
? `!(navigator.doNotTrack == "1" || window.doNotTrack == "1")`
: `true`
}) {
window.dataLayer = window.dataLayer || [];
function gtag(){window.dataLayer && window.dataLayer.push(arguments);}
gtag('js', new Date());
${pluginOptions.trackingIds
.map(
trackingId =>
`gtag('config', '${trackingId}', ${JSON.stringify(gtagConfig)});`
)
.join(``)}
}
`
return setComponents([
<script
key={`gatsby-plugin-google-gtag`}
async
src={`https://www.googletagmanager.com/gtag/js?id=${firstTrackingId}`}
/>,
<script
key={`gatsby-plugin-google-gtag-config`}
dangerouslySetInnerHTML={{ __html: renderHtml() }}
/>,
])
}