feat: Add support for GA4 measurement IDs in GOOGLE_ANALYTICS_ID

This commit is contained in:
Tom Moor
2023-05-08 12:01:35 -04:00
parent a0df79ea5a
commit 1cf597aca7
3 changed files with 24 additions and 19 deletions

View File

@@ -8,7 +8,7 @@ import env from "~/env";
const Analytics: React.FC = ({ children }) => {
// Google Analytics 3
React.useEffect(() => {
if (!env.GOOGLE_ANALYTICS_ID) {
if (!env.GOOGLE_ANALYTICS_ID?.startsWith("UA-")) {
return;
}
@@ -37,25 +37,38 @@ const Analytics: React.FC = ({ children }) => {
// Google Analytics 4
React.useEffect(() => {
if (env.analytics.service !== IntegrationService.GoogleAnalytics) {
const measurementIds = [];
if (env.analytics.service === IntegrationService.GoogleAnalytics) {
measurementIds.push(escape(env.analytics.settings?.measurementId));
}
if (env.GOOGLE_ANALYTICS_ID?.startsWith("G-")) {
measurementIds.push(env.GOOGLE_ANALYTICS_ID);
}
if (measurementIds.length === 0) {
return;
}
const measurementId = escape(env.analytics.settings?.measurementId);
const params = {
allow_google_signals: false,
restricted_data_processing: true,
};
window.dataLayer = window.dataLayer || [];
window.gtag = function () {
window.dataLayer.push(arguments);
};
window.gtag("js", new Date());
window.gtag("config", measurementId, {
allow_google_signals: false,
restricted_data_processing: true,
});
for (const measurementId of measurementIds) {
window.gtag("config", measurementId, params);
}
const script = document.createElement("script");
script.type = "text/javascript";
script.src = `https://www.googletagmanager.com/gtag/js?id=${measurementId}`;
script.src = `https://www.googletagmanager.com/gtag/js?id=${measurementIds.join(
","
)}`;
script.async = true;
document.getElementsByTagName("head")[0]?.appendChild(script);
}, []);