question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Google Analytics does not work with Next.js `Script` tag

See original GitHub issue

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
  Platform: linux
  Arch: x64
  Version: #58~20.04.1-Ubuntu SMP Tue Jun 14 11:29:12 UTC 2022
Binaries:
  Node: 16.14.2
  npm: 8.5.0
  Yarn: 1.22.5
  pnpm: N/A
Relevant packages:
  next: 12.1.6
  react: 18.2.0
  react-dom: 18.2.0

What browser are you using? (if relevant)

Chrome 103.0.5060.53 (Official Build) (64-bit)

How are you deploying your application? (if relevant)

Vercel

Describe the Bug

If I use GA with next/script tag it won’t work. But if I use normal script tag then it works.

GA code snippet with next/script (not working)

<Script
  strategy="afterInteractive"
  src={`https://www.googletagmanager.com/gtag/js?id=${process.env.GA_TRACKING_ID}`}
/>
<Script
  id="ga-tracking"
  strategy="afterInteractive"
  dangerouslySetInnerHTML={{
    __html: `
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', '${process.env.GA_TRACKING_ID}', {
        page_path: window.location.pathname,
      });
    `,
  }}
/>

GA code snippet with regular script tag (working)

<script
  src={`https://www.googletagmanager.com/gtag/js?id=${process.env.GA_TRACKING_ID}`}
/>
<script
  dangerouslySetInnerHTML={{
    __html: `
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', '${process.env.GA_TRACKING_ID}', {
        page_path: window.location.pathname,
      });
    `,
  }}
/>

Expected Behavior

Render the GA script in HTML.

Link to reproduction

https://github.com/brenopolanski/brenopolanski.com/blob/develop/src/pages/_document.tsx#L36

To Reproduce

  1. Run the project;
  2. Inspect the page;
  3. Look for www.googletagmanager.com/gtag/ under the Elements tab.

Screenshot from 2022-06-23 13-04-40

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:8 (1 by maintainers)

github_iconTop GitHub Comments

3reactions
brenopolanskicommented, Jun 28, 2022

As commented above, please give next@canary a try and let us know if it works!

Hey @balazsorban44, it works with the latest version of Next.js (v12.2) if I put next/script inside the _document.tsx file.

Example:

import { Head, Html, Main, NextScript } from 'next/document'
import Script from 'next/script'

export default function Document() {
  return (
    <Html lang="en">
      <Head />
      <body>
        <Main />
        <NextScript />
        <Script
          strategy="afterInteractive"
          src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_TRACKING_ID}`}
        />
      </body>
    </Html>
  )
}

But if I create an Analytics.tsx component and import it into the _document.tsx file it doesn’t work.

Example:

  • Analytics.tsx
import Script from 'next/script'

export const Analytics = () => (
  <Script
    strategy="afterInteractive"
    src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_TRACKING_ID}`}
  />
)
  • _document.tsx
import { Head, Html, Main, NextScript } from 'next/document'

import { Analytics } from '@/components/Analytics'

export default function Document() {
  return (
    <Html lang="en">
      <Head />
      <body>
        <Main />
        <NextScript />
        <Analytics />
      </body>
    </Html>
  )
}
1reaction
balazsorban44commented, Jun 27, 2022

As commented above, please give next@canary a try and let us know if it works!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Google Analytics 4 does not work with Nextjs Script tag
The Next.js Script tag cannot be in the head, it needs to be outside it. See this answer: https://stackoverflow.com/a/68059559/2031033.
Read more >
next-script-for-ga - Next.js
An inline script was used for Google analytics which might impact your webpage's performance. Possible Ways to Fix It. Using gtag.js.
Read more >
How To Set Up Google Analytics With Next.JS Script Component
Let's modify it to place our Google Analytics tracking tags on every page. Firstly we will need to import the Script component from...
Read more >
Google Analytics integration not working in NextJS app
I am working on a NextJS app and want to integrate Google Analytics to track ecommerce data. I have set up a Google...
Read more >
Unblocking Google Analytics With Next.js - Better Programming
The Problem. When I wanted to get a better grasp of my website, I decided to add Google Analytics scripts and faced two...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found