Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NextJS 13: Adding AdSense to the page - Ads seem to be invisible

My goal is to add Google AdSense to a simple NextJS website. I followed the instructions by adding the script tag to the head, the container to the specific pages during pageload I am pushing the ads to the container.

I see that the dom is getting injected with components and the page height will change a bit. So obviously something is happening, but I can't seem to find why I don't see any ads showing up?

Link to the preview: https://quote-van-de-dag.vercel.app/ (turn off adblocker)

PageLayout.tsx

  const pathName = usePathname();
  useEffect(() => {
    var ads = document.getElementsByClassName('adsbygoogle').length;
    for (var i = 0; i < ads; i++) {
      try {
        (window.adsbygoogle = window.adsbygoogle || []).push({});
      } catch (e) {}
    }
  }, [pathName]);

IndexPage.tsx

      <GoogleAdSenseContainer
          client="ca-pub-1265579553508424"
          slot="1768224699"
          responsive={true}
        />

GoogleAdSenseContainer.tsx

   <div
      style={{ overflow: 'hidden' }}
      key={adUnitKey}
    >
      <ins
        className="adsbygoogle"
        style={{ display: 'block' }}
        data-ad-client={client}
        data-ad-slot={slot}
        data-ad-format={responsive && 'auto'}
        data-full-width-responsive={responsive}
      ></ins>
    </div>
like image 344
DennisKr Avatar asked Oct 22 '25 04:10

DennisKr


2 Answers

The script should be loaded with beforeInteractive strategy.

import Script from 'next/script';

export default function(){
  return (<>
   <Script 
    id="adsbygoogle-init" 
    strategy="beforeInteractive" 
    crossOrigin="anonymous"
   src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxxx"></Script>
  <ins className="adsbygoogle"
    style={{ display: 'block' }}
    data-ad-client="ca-pub-xxx"
    data-ad-slot="xxx"
    data-ad-format="auto"
    data-full-width-responsive="true"
  />
  </>);
}

like image 162
cwtuan Avatar answered Oct 23 '25 18:10

cwtuan


Try this package named nextjs13_google_adsense via npm install nextjs13_google_adsense or yarn add nextjs13_google_adsense.

after installing the package insert your google adsense ad unit code like this

import GoogleAdUnit from 'nextjs13_google_adsense'

export default function MyPage() {
  return <>
  <div>Test Title</div>
  <GoogleAdUnit>
    <ins
          className="adsbygoogle"
          style={{ display: 'block', width: '100%' }}
          data-ad-client="ca-pub-1234567890"
          data-ad-slot="123456"
          data-ad-format="auto"
          data-full-width-responsive="true"
        ></ins>
  </GoogleAdUnit>
  <div>Test Content
  <>;
}
like image 40
shriekdj Avatar answered Oct 23 '25 18:10

shriekdj