Home > References > Web Development > Nextjs references

How to use google adsense in Next Js

Last updated : June 12, 2021

Using Adsense in Next js needs a different approach compared to a traditional request-based website. This article explains how to use dynamically inserted Google Adsense ad units in a Next js application. You will be able to retrieve and display ad units embedded in your post pages.

Traditional Google AdSense implementation most of the time does not work with websites built with Next js. Meaning, the traditional Adsense implementation in Next js works in some situations but not always. In this article, I will explain when it works and when it doesn't. We will also look at how to implement Adsense for websites built with Next js.

If you have already registered with Google Adsense, you may have the Ad code handy to be inserted into your HTML code. Your ad code may look like below.

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-xxxxxxxx"
     data-ad-slot="xxxxxxxx"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>

Note that if you have multiple ads in one page, you don't need to repeat adsbygoogle.js with each ad unit.

How to place Adsense script on a Next js page?

In Next js, you only need to load the adsbygoogle.js once when your page is initially loaded. That means you will have to pick a page that always loads regardless of the page visitors land on. If you have a layout page that assembles other page components, that would be an ideal place to put the adsbygoogle.js.

If you have a hard time finding such a page, _document.js will do the job. I usually use my layout page to load one-time scripts. That way, I have dynamic control over what needs to be loaded, which _document.js lacks.

Figure 1 : Next js layout page as global page

Go ahead and place <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> script in the <head> section of your global page.

How to place Adsense ad units on a Next js page?

Remember I mentioned situations that don't always work with Next js? For the sake of understanding, I will do some explanations.

Now place the remaining of the script on places where you want to show ads on your page.

<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-xxxxxxxx"
     data-ad-slot="xxxxxxxx"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>

This is the Adsense standard implementation. This approach works in some situations but not always.

When is standard AdSense implementation doesn't work with Next js?

The standard Adsense implementation works in Next js only with the initial page load or page refresh. Any internal navigation that occurs with Next Link does not trigger Adsense. Therefore, your visitors will see ads on pages they land, not on pages they navigate through internal links.

Why is standard AdSense implementation doesn't work with Next js?

In Google Adsense, each ad unit needs individual initialization by running (adsbygoogle = window.adsbygoogle || []).push({}); In other words, five ad units need five pushes by running the script five times. In Next js, page scripts are executed only when the page is initially loaded or refreshed. That's the reason the standard Google Adsense implementation doesn't always work with Next js. Any subsequent internal navigation that happens with Next links does not trigger page scripts, therefore (adsbygoogle = window.adsbygoogle || []).push({}) is not executed at all. In traditional request-based websites, each navigation or link click is a page refresh, and Adsense scrips are always executed.

How to make AdSense work with Next js?

There is no standard or a unique way to do this. But I will show you one way to solve the problem. Our goal is to execute the push script (adsbygoogle = window.adsbygoogle || []).push({}) to every ad unit we have in the page.

Step 1: Reformat ad units as below

Remove the script from each ad unit.

<script>
	(adsbygoogle = window.adsbygoogle || []).push({});
</script>

So, your each ad unit will look like below.

<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-xxxxxxxx"
     data-ad-slot="xxxxxxxx"
     data-ad-format="auto"
     data-full-width-responsive="true">
</ins>

Step 2: Identify a global page

As we discussed earlier, this can be your layout page or _document.js page. Create a useEffect() hook in preparation to initialize ad units.

useEffect(() => {
}, []);

Step 3: Initialize all the ad units on the page

If your ad unit count is always the same, execute the (adsbygoogle = window.adsbygoogle || []).push({}) script number of times equivalent to the number of ad units.

Our solution assumes the number of ad units on each page can vary.

In order to execute the push script for each occurrence of the ad unit, we need to know how many ad units are on the page.

We can use the existing ad unit class name "adsbygoogle" to count the number of ad unit occurrences. And execute the push script an equivalent number of times.

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

Considerations

This solution will solve the Adsense problem with Next js applications. If you have any client-side rendered components on your page like sidebars loaded asynchronously, you need to ensure the Adsense initialization script is triggered after all the ad units are loaded on the scren.

Lance
By: Lance
Lance is a software engineer with over 15 years of experience in full-stack software development.
Read more...

Leave a comment

No Comments