Search code examples
reactjsnext.jsadsense

Adsense Ad Units Next.js


I need help implementing adsense ad units in nextjs. I'm already using the auto generated ads and it's working fine, but I'd like to personalize it a bit. This is what I got so far but I'm unsure if that is the best way.

I created an ad unit in my adsense account and then made a component with the code snippet:

GoogleAds.jsx:

 import React from "react";

 function GoogleAds() {
  return (
    <div>
      <script
        async
        src="xxxxxxxxxxx"
        crossorigin="anonymous"
      ></script>
      {/* <!-- Rectangular ad unit --> */}
      <ins
        class="adsbygoogle"
        className="adsbygoogle"
        // style={"display:block"} (removed this and added a className instead)
        data-ad-client="xxxxxxxxxxx"
        data-ad-slot="xxxxxxxxxxx"
        data-ad-format="auto"
        data-full-width-responsive="true"
      ></ins>
      <script>(adsbygoogle = window.adsbygoogle || []).push({});</script>
    </div>
  );
}

export default GoogleAds;

Then, I'm importing it as a component to my [slug].js. I haven't found a way of testing it out since my website is already live and I don't want to be testing things live when ppl are trying to visit my page (not sure if an alternative exist, happy to hear suggestions). Also, I statically generate my page, so I don't have to use a server, and I'm wondering if a useEffect alone would do the trick.

Finally, I'm trying not to use any additional npm packages.

Thanks in advance for all of your help!


Solution

  • Is the question how to test your implementation? You can generate page locally and open on localhost. Then you can check if you see created in your element. If you see iframe - it should work in production.

    Overall it looks correct. Though I would call adsbygoogle.push() from your JS code once HTML is rendered (in onMounted or whatever its analog in react).

    Also you need to add <script src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js></script> only once per page. So as long as you add it somewhere in - you don't need to include it in every single ad unit.