Google Tag Manager
Unanswered
Hilsa shad posted this in #help-forum
Hilsa shadOP
I'm trying to add GTM to my project but can't find a good Blog or Documentation that explains how to do it with the latest APP Routes approach. Someone could help me please? I'd really appreciate it. Thanks!
5 Replies
Mossyrose gall wasp
"use client";
import { usePathname, useSearchParams } from "next/navigation";
import Script from "next/script";
import { useEffect } from "react";
import { GTM_ID, pageview } from "@/utils/lib/gtm";
const Analytics = () => {
const pathname = usePathname();
const searchParams = useSearchParams();
useEffect(() => {
if (pathname) {
pageview(pathname);
}
}, [pathname, searchParams]);
if (process.env.NEXT_PUBLIC_VERCEL_ENV === "development") {
return null;
}
return (
<>
<noscript>
<iframe
src={`https://www.googletagmanager.com/ns.html?id=GTM-YOUR_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-YOUR_GTM_ID');
`,
}}
/>
</>
);
};
export default Analytics;in my latest project i made this one it works very well you should add this to root layout and wrap it with Suspense
lib/gtm.ts
type WindowWithDataLayer = Window & {
dataLayer: Record<string, any>[];
};
declare const window: WindowWithDataLayer;
export const GTM_ID = process.env.NEXT_PUBLIC_GTM;
export const pageview = (url: string) => {
if (typeof window.dataLayer !== "undefined") {
window.dataLayer.push({
event: "pageview",
page: url,
});
} else {
console.log({
event: "pageview",
page: url,
});
}
};Hilsa shadOP
Thank you! That worked 😄
Mossyrose gall wasp
you are welcome, happy to help 🙂