Add Google Analytics to NextJS/React Website

Sh Raj - Mar 23 - - Dev Community
⨯ src/app/[...slug]/layout.js (50:11) @ dataLayer
⨯ ReferenceError: dataLayer is not defined
Enter fullscreen mode Exit fullscreen mode

https://dev.sh20raj.com/sh20raj/add-google-analytics-to-nextjs-website-11gp

if your add like that

        <script
          async
          src="https://www.googletagmanager.com/gtag/js?id=G-X1234"
        ></script>
        <script>
          window.dataLayer = window.dataLayer || []; function gtag()
          {dataLayer.push(arguments)}
          gtag('js', new Date()); gtag('config', 'G-X1234');
        </script>
Enter fullscreen mode Exit fullscreen mode

Error will be shown like

 ⨯ src/app/[...slug]/layout.js (50:11) @ dataLayer
 ⨯ ReferenceError: dataLayer is not defined
    at RootLayout (./src/app/[...slug]/layout.js:170:29)
  48 |         <script>
  49 |           window.dataLayer = window.dataLayer || []; function gtag()
> 50 |           {dataLayer.push(arguments)}
     |           ^
  51 |           gtag('js', new Date()); gtag('config', 'G-X1234');
  52 |         </script>
  53 |         <script
Enter fullscreen mode Exit fullscreen mode

for Fixing it add Like ( wrap it with a {} with backticks )


        <script
          async
          src="https://www.googletagmanager.com/gtag/js?id=G-CWL59Y4TR7"
        ></script>
        <script>
          {`window.dataLayer = window.dataLayer || []; function gtag()
          {dataLayer.push(arguments)}
          gtag('js', new Date()); gtag('config', 'G-CWL59Y4TR7');`}
        </script>
Enter fullscreen mode Exit fullscreen mode

Additionally you can use Script and https://nextjs.org/docs/messages/next-script-for-ga

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .