Skip to content

Commit

Permalink
[docs] Support Google Analytics 4 (#36123)
Browse files Browse the repository at this point in the history
Co-authored-by: Olivier Tassinari <[email protected]>
  • Loading branch information
alexfauquette and oliviertassinari authored Mar 29, 2023
1 parent ae98db6 commit 417ee3b
Show file tree
Hide file tree
Showing 5 changed files with 87 additions and 8 deletions.
12 changes: 12 additions & 0 deletions docs/data/material/components/material-icons/SearchIcons.js
Original file line number Diff line number Diff line change
Expand Up @@ -138,12 +138,20 @@ const Icons = React.memo(function Icons(props) {
eventAction: 'click',
eventLabel: icon.name,
});
window.gtag('event', 'material-icons', {
eventAction: 'click',
eventLabel: icon.name,
});
window.ga('send', {
hitType: 'event',
eventCategory: 'material-icons-theme',
eventAction: 'click',
eventLabel: icon.theme,
});
window.gtag('event', 'material-icons-theme', {
eventAction: 'click',
eventLabel: icon.theme,
});
}
};

Expand Down Expand Up @@ -499,6 +507,10 @@ export default function SearchIcons() {
eventAction: 'no-results',
eventLabel: value,
});
window.gtag('event', 'material-icons', {
eventAction: 'no-results',
eventLabel: value,
});
}
});
}
Expand Down
10 changes: 9 additions & 1 deletion docs/pages/_app.js
Original file line number Diff line number Diff line change
Expand Up @@ -230,8 +230,9 @@ MyApp.getInitialProps = async ({ ctx, Component }) => {

// Track fraction of actual events to prevent exceeding event quota.
// Filter sessions instead of individual events so that we can track multiple metrics per device.
// See https://github.com/GoogleChromeLabs/web-vitals-report to use this data
const disableWebVitalsReporting = Math.random() > 0.0001;
export function reportWebVitals({ id, name, label, value }) {
export function reportWebVitals({ id, name, label, delta, value }) {
if (disableWebVitalsReporting) {
return;
}
Expand All @@ -243,4 +244,11 @@ export function reportWebVitals({ id, name, label, value }) {
eventLabel: id, // id unique to current page load
nonInteraction: true, // avoids affecting bounce rate.
});
window.gtag('event', name, {
value: delta,
metric_label: label === 'web-vital' ? 'Web Vitals' : 'Next.js custom metric',
metric_value: value,
metric_delta: delta,
metric_id: id, // id unique to current page load
});
}
30 changes: 25 additions & 5 deletions docs/pages/_document.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as React from 'react';
import Script from 'next/script';
import { ServerStyleSheets as JSSServerStyleSheets } from '@mui/styles';
import { ServerStyleSheet } from 'styled-components';
import createEmotionServer from '@emotion/server/create-instance';
Expand Down Expand Up @@ -33,8 +34,11 @@ if (process.env.NODE_ENV === 'production') {
const PRODUCTION_GA =
process.env.DEPLOY_ENV === 'production' || process.env.DEPLOY_ENV === 'staging';

// TODO remove https://support.google.com/analytics/answer/11986666
const GOOGLE_ANALYTICS_ID = PRODUCTION_GA ? 'UA-106598593-2' : 'UA-106598593-3';

const GOOGLE_ANALYTICS_ID_V4 = PRODUCTION_GA ? 'G-5NXDQLC2ZK' : 'G-XJ83JQEK7J';

export default class MyDocument extends Document {
render() {
const { canonicalAsServer, userLanguage } = this.props;
Expand Down Expand Up @@ -153,13 +157,29 @@ export default class MyDocument extends Document {
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{
__html: `
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
window.ga('create','${GOOGLE_ANALYTICS_ID}',{
sampleRate: ${PRODUCTION_GA ? 80 : 100},
});
`,
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
window.ga('create','${GOOGLE_ANALYTICS_ID}',{
sampleRate: ${PRODUCTION_GA ? 80 : 100},
});
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
window.gtag = gtag;
gtag('js', new Date());
gtag('config', '${GOOGLE_ANALYTICS_ID_V4}', {
send_page_view: false,
});
`,
}}
/>
{/**
* A better alternative to <script async>, to delay its execution
* https://developer.chrome.com/blog/script-component/
*/}
<Script
strategy="afterInteractive"
src={`https://www.googletagmanager.com/gtag/js?id=${GOOGLE_ANALYTICS_ID_V4}`}
/>
<NextScript />
</body>
</Html>
Expand Down
8 changes: 8 additions & 0 deletions docs/src/modules/components/Ad.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@ class AdErrorBoundary extends React.Component {
eventAction: 'crash',
eventLabel,
});
window.gtag('event', 'ad', {
eventAction: 'crash',
eventLabel,
});
}

render() {
Expand Down Expand Up @@ -197,6 +201,10 @@ function Ad() {
eventAction: 'display',
eventLabel,
});
window.gtag('event', 'ad', {
eventAction: 'display',
eventLabel,
});
}, 2500);

return () => {
Expand Down
35 changes: 33 additions & 2 deletions docs/src/modules/components/GoogleAnalytics.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ function handleClick(event) {
eventAction: element.getAttribute('data-ga-event-action'),
eventLabel: element.getAttribute('data-ga-event-label'),
});
window.gtag('event', category, {
eventAction: element.getAttribute('data-ga-event-action'),
eventLabel: element.getAttribute('data-ga-event-label'),
});
break;
}

Expand All @@ -60,24 +64,39 @@ function GoogleAnalytics() {
}, []);

const router = useRouter();
const timeout = React.useRef();

React.useEffect(() => {
// Wait for the title to be updated.
setTimeout(() => {
// React fires useEffect twice in dev mode
clearTimeout(timeout.current);
timeout.current = setTimeout(() => {
const { canonicalAsServer } = pathnameToLanguage(window.location.pathname);
window.ga('set', { page: canonicalAsServer });
window.ga('send', { hitType: 'pageview' });

// https://developers.google.com/analytics/devguides/collection/ga4/views?client_type=gtag
window.gtag('event', 'page_view', {
page_title: document.title,
page_location: canonicalAsServer,
});
});
}, [router.route]);

const codeVariant = useNoSsrCodeVariant();
React.useEffect(() => {
window.ga('set', 'dimension1', codeVariant);
window.gtag('set', 'user_properties', {
codeVariant,
});
}, [codeVariant]);

const userLanguage = useUserLanguage();
React.useEffect(() => {
window.ga('set', 'dimension2', userLanguage);
window.gtag('set', 'user_properties', {
userLanguage,
});
}, [userLanguage]);

React.useEffect(() => {
Expand All @@ -88,6 +107,9 @@ function GoogleAnalytics() {
function trackDevicePixelRation() {
const devicePixelRatio = Math.round(window.devicePixelRatio * 10) / 10;
window.ga('set', 'dimension3', devicePixelRatio);
window.gtag('set', 'user_properties', {
devicePixelRatio,
});
}

trackDevicePixelRation();
Expand All @@ -111,8 +133,17 @@ function GoogleAnalytics() {

React.useEffect(() => {
window.ga('set', 'dimension4', colorSchemeOS);
window.gtag('set', 'user_properties', {
colorSchemeOS,
});
}, [colorSchemeOS]);

React.useEffect(() => {
window.ga('set', 'dimension5', colorScheme);
}, [colorSchemeOS, colorScheme]);
window.gtag('set', 'user_properties', {
colorScheme,
});
}, [colorScheme]);

return null;
}
Expand Down

0 comments on commit 417ee3b

Please sign in to comment.