Use Google Tag Manager in Nest.js
February 24, 2022
This is a way to use Google Tag Manager in Nest.js.
1. Issue a Google Tag Manager ID
Register at the following URL.
https://tagmanager.google.com/
2. Set the Google Tag Manager ID to an environment variable
.env.local
# Google Tag Manager
NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID=GTM-******
3. Add the following code to the Application
globals.d.ts
interface Window {
gtag: (...args: any[]) => void;
dataLayer: Record<string, any>;
}
lib/gtm.ts
export const GTM_ID = process.env.NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID
export const pageview = (url) => {
window.dataLayer.push({
event: 'pageview',
page: url,
})
}
pages/_app.ts
import React, { useEffect } from "react";
import type { AppProps } from "next/app";
import { useRouter } from "next/router";
import Script from "next/script";
import "../styles/globals.css";
import { GTM_ID, pageview } from "../lib/gtm";
const MyApp = ({ Component, pageProps }: AppProps): JSX.Element => {
const router = useRouter();
useEffect(() => {
router.events.on("routeChangeComplete", pageview);
return () => {
router.events.off("routeChangeComplete", pageview);
};
}, [router.events]);
return (
<>
<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}');
`,
}}
/>
<Component {...pageProps} />
</>
);
};
export default MyApp;
pages/_document.tsx
import Document, { Html, Head, Main, NextScript } from 'next/document'
import { GTM_ID } from '../lib/gtm'
export default class MyDocument extends Document {
render() {
return (
<Html>
<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>
</Html>
)
}
}