Skip to content

Instantly share code, notes, and snippets.

@alanhchoi
Last active February 5, 2022 11:07
Show Gist options
  • Save alanhchoi/cbe086319dad387bd09c0d2c9b09c193 to your computer and use it in GitHub Desktop.
Save alanhchoi/cbe086319dad387bd09c0d2c9b09c193 to your computer and use it in GitHub Desktop.
import escapeRegExp from 'lodash/escapeRegExp';
import { useRouter } from 'next/router';
import Script from 'next/script';
import { useEffect } from 'react';
import { pageTitleSuffix } from '~/components/PageTitle';
function removeSuffixFromTitle(title: string) {
return title.replace(new RegExp(`${escapeRegExp(pageTitleSuffix)}$`), '');
}
export default function useGoogleAnalyticsScript() {
const router = useRouter();
const gaMeasurementId = process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID;
useEffect(() => {
if (!gaMeasurementId) {
return undefined;
}
window.gtag('config', gaMeasurementId, {
page_title: removeSuffixFromTitle(document.title),
});
const handleRouteChange = () => {
window.gtag('event', 'page_view', {
page_title: removeSuffixFromTitle(document.title),
});
};
router.events.on('routeChangeComplete', handleRouteChange);
return () => {
router.events.off('routeChangeComplete', handleRouteChange);
};
}, [gaMeasurementId, router.events]);
if (!gaMeasurementId) {
return null;
}
return (
<>
<Script
src={`https://www.googletagmanager.com/gtag/js?id=${gaMeasurementId}`}
strategy="afterInteractive"
/>
<Script id="google-analytics" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){window.dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${gaMeasurementId}');
`}
</Script>
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment