Next.js Discord

Discord Forum

How to insert Google analytic/tag manager correctly?

Unanswered
Fire ant posted this in #help-forum
Open in Discord
Fire antOP
Using Head tag it says i need to remove Script tag from Head component, so how do i use google analytic for nextjs 14 app dir? To make sure all script was in head tag?

8 Replies

Spectacled bear
In my case I created GoogleTagManager.tsx
import Script from "next/script";

type Props = {
  id: string;
  gtmId: string;
};

export function GoogleTagManager({ id, gtmId }: Props) {
  return (
    <>
      <Script id={id} strategy="afterInteractive">
        {`(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','${gtmId}');`}
      </Script>
      <noscript>
        <iframe
          title="gtm-ns"
          src={`https://www.googletagmanager.com/ns.html?id=${gtmId}`}
          height="0"
          width="0"
          style={{
            display: "none",
            visibility: "hidden",
          }}
        />
      </noscript>
    </>
  );
}
AnalyticsScripts.tsx
import { GoogleTagManager } from "./GoogleTagManager";


export const AnalyticsScripts = () => {
  return (
    <>
      <GoogleTagManager
        id="google-tag-manager"
        gtmId={<gtmId>}
      />
      ...other <Script/>
    </>
  );
};
and after we add in in app/layout.tsx
export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html>
      <body>
        <AnalyticsScripts />
        {children}
      </body>
    </html>
  );
}
Fire antOP
Your code looks almost like mine, but without props
Giant panda
This script will be blocked by browsers such as breave or safari?