Home > database >  Google adsense doesn't see code fragment in the header of nextjs site
Google adsense doesn't see code fragment in the header of nextjs site

Time:10-30

Hello im trying to setup google adsense on my nextjs site but it isn't seen by adsense, adsense keeps saying i have to place the code inside of my headers. How can i do it properly? This is my _document.js:

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

function Document() {
  return (
    <Html>
      <Head>
        <link rel="icon" href="/images/logo1.ico" />
        <link rel="apple-touch-icon" href="/images/logo1.png" />
        <link rel="manifest" href="/images/manifest.json" />
        <Script
           id="Adsense-id"
           data-ad-client="ca-pub-**********"
           async="true"
           strategy="beforeInteractive"
            src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
        />
        <Script
            src={"https://www.googletagmanager.com/gtag/js?id=G-*******"}
            strategy="afterInteractive"
          />
        <Script id="google-analytics" strategy="afterInteractive">
          {`
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());

            gtag('config', 'G-********');
          `}
        </Script>
    </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  )
}

export default Document;

The Google Analytics in the same file do work.

Chrome dev tools screenshot

CodePudding user response:

To prevent cross-site-scripting, React will covert that google analytics block into a string, rendering it useless. You'll need to use dangerouslySetInnerHTML to get the job done, or use a library.

<Head>
  ...
  <script
    async 
    dangerouslySetInnerHTML={{
      __html: `window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
  
      gtag('config', ${YOUR_TRACKING_ID});`
    }}
  />
</Head>
  • Related