Inject Google Analytics when tracker ID is in the environment

This commit is contained in:
Kimmo Puputti 2017-10-25 13:15:49 +03:00
parent e276ebb4a6
commit 945f6d4862
2 changed files with 20 additions and 0 deletions

View file

@ -6,6 +6,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--!meta-->
<!--!googleAnalyticsScript-->
<link rel="manifest" href="%PUBLIC_URL%/static/manifest.json">
<link rel="icon" sizes="32x32" type="image/x-icon" href="%PUBLIC_URL%/static/favicon.ico">
<link rel="icon" sizes="192x192" type="image/png" href="%PUBLIC_URL%/static/webapp-icon-192x192.png" />

View file

@ -108,6 +108,23 @@ exports.render = function(requestUrl, context, preloadedState) {
<script>window.__PRELOADED_STATE__ = ${JSON.stringify(serializedState)};</script>
`;
// We want to precicely control where the analytics script is
// injected in the HTML file so we can catch all events as early as
// possible. This is why we inject the GA script separately from
// react-helmet. This script also ensures that all the GA scripts
// are added only when the proper env var is present.
//
// See: https://developers.google.com/analytics/devguides/collection/analyticsjs/#alternative_async_tracking_snippet
const googleAnalyticsScript = process.env.REACT_APP_GOOGLE_ANALYTICS_ID
? `
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', '${process.env.REACT_APP_GOOGLE_ANALYTICS_ID}', 'auto');
</script>
<script async src="https://www.google-analytics.com/analytics.js"></script>
`
: '';
return template({
htmlAttributes: head.htmlAttributes.toString(),
title: head.title.toString(),
@ -115,6 +132,7 @@ exports.render = function(requestUrl, context, preloadedState) {
meta: head.meta.toString(),
script: head.script.toString(),
preloadedStateScript,
googleAnalyticsScript,
body,
});
};