From 945f6d48626ac7f06900750b2a03f2d280e26a84 Mon Sep 17 00:00:00 2001 From: Kimmo Puputti Date: Wed, 25 Oct 2017 13:15:49 +0300 Subject: [PATCH] Inject Google Analytics when tracker ID is in the environment --- public/index.html | 2 ++ server/renderer.js | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/public/index.html b/public/index.html index a4810318..a3bcc5f5 100644 --- a/public/index.html +++ b/public/index.html @@ -6,6 +6,8 @@ + + diff --git a/server/renderer.js b/server/renderer.js index dc3e0349..50f68e21 100644 --- a/server/renderer.js +++ b/server/renderer.js @@ -108,6 +108,23 @@ exports.render = function(requestUrl, context, preloadedState) { `; + // 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 + ? ` + + + ` + : ''; + 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, }); };