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>
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"
/>
</>);
}
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
<>;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With