Skip to content

Commit

Permalink
Using Google Tag Manager
Browse files Browse the repository at this point in the history
  • Loading branch information
NPJigaK committed Oct 25, 2023
1 parent cbb725d commit a777303
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 77 deletions.
17 changes: 17 additions & 0 deletions lib/gtm.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { debugLogger } from "./debugLogger";

declare global {
interface Window {
dataLayer: Record<string, any>[];
}
}

export const GTM_ID = "GTM-NDPCVWBM";

export const pageview = (url: string): void => {
debugLogger(`Logging pageview for ${url}`);
window.dataLayer.push({
event: "pageview",
page: url,
});
};
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
"nextra-theme-docs": "3.0.0-alpha.8",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-ga4": "^2.1.0",
"react-social-login-buttons": "3.9.1"
},
"devDependencies": {
Expand Down
54 changes: 23 additions & 31 deletions pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,45 +3,37 @@ import type { AppProps } from "next/app";
import type { ReactElement } from "react";
import { useEffect } from "react";
import { useRouter } from "next/router";
import ReactGA from "react-ga4";
import { debugLogger } from "@/lib/debugLogger";

export const logPageView = () => {
debugLogger(`Logging pageview for ${window.location.pathname}`);
ReactGA.set({ page: window.location.pathname });
ReactGA.send({ hitType: "pageview", page: window.location.pathname });
};

export const initGA = () => {
debugLogger("init GA");
ReactGA.initialize("G-EPBVRTSKFD");
};
import Script from "next/script";
import { GTM_ID, pageview } from "@/lib/gtm";

export default function App({ Component, pageProps }: AppProps): ReactElement {
const router = useRouter();

useEffect(() => {
if (window.location.hostname === "localhost") {
debugLogger("Running on localhost. Skip initGA.");
return;
}
initGA();
// `routeChangeComplete` won't run for the first page load unless the query string is
// hydrated later on, so here we log a page view if this is the first render and
// there's no query string
if (!router.asPath.includes("?")) {
logPageView();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

useEffect(() => {
// Listen for page changes after a navigation or when the query changes
router.events.on("routeChangeComplete", logPageView);
router.events.on("routeChangeComplete", pageview);
return () => {
router.events.off("routeChangeComplete", logPageView);
router.events.off("routeChangeComplete", pageview);
};
}, [router.events]);

return <Component {...pageProps} />;
return (
<>
{/* Google Tag Manager - Global base code */}
<Script
id="gtag-base"
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}');
`,
}}
/>
<Component {...pageProps} />
</>
);
}
49 changes: 9 additions & 40 deletions pages/_document.tsx
Original file line number Diff line number Diff line change
@@ -1,50 +1,19 @@
import { GTM_ID } from "@/lib/gtm";
import Document, { Html, Head, Main, NextScript } from "next/document";

// interface LangSettingDocumentProps extends DocumentInitialProps {
// lang: string;
// }

// class LangSettingDocument extends Document<LangSettingDocumentProps> {
// static async getInitialProps(ctx: any) {
// const supportedLocales = {
// en: "en-US",
// es: "es-ES",
// pt: "pt-BR",
// ru: "ru-RU",
// de: "de-DE",
// fr: "fr-FR",
// ja: "ja-JP",
// ko: "ko-KR",
// };
// const initialProps = await Document.getInitialProps(ctx);
// const { pathname } = ctx;
// const localEntry = Object.entries(supportedLocales).find((entry) =>
// pathname.startsWith(`/${entry[0]}`)
// );
// const lang = localEntry ? localEntry[1] : "en-US";
// return { ...initialProps, lang };
// }

// render() {
// return (
// <Html lang={this.props.lang}>
// <Head />
// <body>
// <Main />
// <NextScript />
// </body>
// </Html>
// );
// }
// }

// export default LangSettingDocument;

const LangSettingDocument = ({ lang }: any) => {
return (
<Html lang={lang}>
<Head />
<body>
<noscript>
<iframe
src={`https://www.googletagmanager.com/ns.html?id=${GTM_ID}`}
height="0"
width="0"
style={{ display: "none", visibility: "hidden" }}
/>
</noscript>
<Main />
<NextScript />
</body>
Expand Down
5 changes: 0 additions & 5 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4863,11 +4863,6 @@ [email protected], react-dom@^18.2.0:
loose-envify "^1.1.0"
scheduler "^0.23.0"

react-ga4@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/react-ga4/-/react-ga4-2.1.0.tgz#56601f59d95c08466ebd6edfbf8dede55c4678f9"
integrity sha512-ZKS7PGNFqqMd3PJ6+C2Jtz/o1iU9ggiy8Y8nUeksgVuvNISbmrQtJiZNvC/TjDsqD0QlU5Wkgs7i+w9+OjHhhQ==

react-is@^16.13.1, react-is@^16.7.0:
version "16.13.1"
resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4"
Expand Down

0 comments on commit a777303

Please sign in to comment.