maurijn.vd
maurijn.vd

Reputation: 131

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

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

Upvotes: 2

Views: 410

Answers (2)

The Last Spark
The Last Spark

Reputation: 1

Turns out my website was only being served over https, and google ad cralwer only works over http, so I had to add an nginx redirect to the 443 and it works!

Upvotes: 0

Andy Hoffman
Andy Hoffman

Reputation: 19109

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>

Upvotes: 2

Related Questions