fix: Swap out GTM provider

This commit is contained in:
Sol Irvine 2023-09-06 16:23:57 -07:00
parent c65e703e41
commit fb8a1924bb
3 changed files with 74 additions and 8 deletions

View File

@ -0,0 +1,47 @@
'use client';
import { GTM_ID, pageview } from 'lib/gtm';
import { usePathname, useSearchParams } from 'next/navigation';
import Script from 'next/script';
import { useEffect } from 'react';
export default function Analytics() {
const pathname = usePathname();
const searchParams = useSearchParams();
useEffect(() => {
if (pathname) {
pageview(pathname);
}
}, [pathname, searchParams]);
if (process.env.NEXT_PUBLIC_VERCEL_ENV !== 'production') {
return null;
}
return (
<>
<noscript>
<iframe
src={`https://www.googletagmanager.com/ns.html?id=${GTM_ID}`}
height="0"
width="0"
style={{ display: 'none', visibility: 'hidden' }}
/>
</noscript>
<Script
id="gtm-script"
strategy="afterInteractive"
dangerouslySetInnerHTML={{
__html: `
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer', '${GTM_ID}');
`
}}
/>
</>
);
}

View File

@ -2,10 +2,10 @@ import { Lato, Noto_Serif_JP } from 'next/font/google';
import localFont from 'next/font/local';
import { ReactNode, Suspense } from 'react';
import { GoogleProvider } from 'app/context/google-provider';
import { SupportedLocale } from 'components/layout/navbar/language-control';
import { NextIntlClientProvider } from 'next-intl';
import { notFound } from 'next/navigation';
import Analytics from './analytics';
import './globals.css';
const { TWITTER_CREATOR, TWITTER_SITE, SITE_NAME } = process.env;
@ -88,8 +88,6 @@ export default async function RootLayout({
notFound();
}
const shouldTrack = process.env.NODE_ENV === 'production';
return (
<html
lang={params.locale}
@ -97,11 +95,10 @@ export default async function RootLayout({
>
<body className="bg-dark text-white selection:bg-green-800 selection:text-green-400">
<NextIntlClientProvider locale={params?.locale} messages={messages}>
<GoogleProvider isShowing={shouldTrack}>
<Suspense>
<main>{children}</main>
</Suspense>
</GoogleProvider>
<Suspense>
<Analytics />
<main>{children}</main>
</Suspense>
</NextIntlClientProvider>
</body>
</html>

22
lib/gtm.ts Normal file
View File

@ -0,0 +1,22 @@
// lib/gtm.ts
type WindowWithDataLayer = Window & {
dataLayer: Record<string, any>[];
};
declare const window: WindowWithDataLayer;
export const GTM_ID = process.env.NEXT_PUBLIC_GTM_ID;
export const pageview = (url: string) => {
if (typeof window.dataLayer !== 'undefined') {
window.dataLayer.push({
event: 'pageview',
page: url
});
} else {
console.debug({
event: 'pageview',
page: url
});
}
};