Place google adsense to your next-js project.

Place google adsense to your next-js project.

Post by: Niraj Dhungana

Posted on: Nov 24, 2021

#Next JS# Adsense

If you do not find a way to make money while you sleep, you will work until you die. - Warren Buffett

And I think google adsense is a great way to make extra income while you sleep. So, let’s see how we can add google adsense inside our Next JS app.

The website you are reading this post on was one of my dream projects. I made this website with Next JS, MongoDB, Cloudinary and a whole lot of other things.

There are a lot of places where I got stuck while developing this website. And one of the most important parts where I got stuck was while adding Adsense to my next-js website.

Problem with adsense and Next JS

The main problem while adding Adsense to next-js website is that Adsense injects it’s HTML code at the beginning while the website is loading.

If you have a website where you have pre generated pages with methods like getStaticProps and if you try to render advertisements to those pages with the default setup.

You will lose your styling. Those ads will stay where they were previously rendered, and they'll appear in the same location even if you change the route.

BTW this is not the problem with Adsense. This is how the next js works. It doesn’t load the page every time you change the route.

Let's add adsense inside next-js

Now we know the problem. So, let’s solve it.

First of all we need to add the adsense code to our head tag. And the best place to do that in next-js is _document.js. If you don’t have this file, place it inside the pages folder.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// ./pages/_document.js
class MyDocument extends Document {
/* rest */
render (
/* ... */
    <Head>
    {/* google adsense */}
    <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" />
    <script dangerouslySetInnerHTML={{
        __html: `
        (adsbygoogle = window.adsbygoogle || []).push({
            google_ad_client: "YOUR_CLIENT_ID",
            enable_page_level_ads: true
            });
            `,
            }} />
</Head>

You need to add these two script tags inside the head tag of your _document and don’t forget to change your adsense_id (which you will get from google adsense). Don’t worry you can show this ID publicly.

Now we are legally ready to place google ads on your next-js website. But to solve the problem which we talk about above. We need to create a Component which we will use to place advertisements inside different pages.

Create a new component called Adsense or whatever you like. Then this is the code which you need to copy and paste inside your brand new component.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import React, { useEffect } from "react";

export default function Adsense() {
  const loadAds = () => {
    try {
      if (typeof window !== "undefined") {
        (window.adsbygoogle = window.adsbygoogle || []).push({});
      }
    } catch (error) {
      console.log("adsense error", error.message);
    }
  };

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

  return (
    <ins
      className="adsbygoogle"
      style={{ display: "block" }}
      data-ad-client="********"
      data-ad-slot="********"
      data-ad-format="auto"
      data-full-width-responsive="true"
    ></ins>
  );
}

The most important thing inside this code block is. Number one change those fake data-ad-client and data-ad-slot with the code you got from adsense account.

Tip: If you don’t know where you can get the client and slot id. Go to your adsense dashboard.

  • Click on Ads > Overview
  • Go to By ad unit
  • If you have old ads click on get code.
  • Or you can create a new ad and copy the code.

Number two and the most important. Here we are using useEffect hook to load advertisements and I am wrapping the code to push add inside the try catch block.

Inside next-js if adsense through any error then your entire page will be crashed with weird error messages. So, this is the protection for that.

Note: the reasons for adsense errors are.

  • No sufficient width and height is provided to render google ads.

  • Trying to push multiple ads. If you want to see this error you can simply remove [] from inside the useEffect hook and if you refresh or change the route you will get the beautiful error.

  • Using wrong adsense id.

Now wherever you want to place google ads you can use this <Adsense /> component or the component you made. You will not see any ad if you are in development mode. Inside your console you will see an error with response code 403.

But don’t worry if you have correct google adsense id then you will see those ads on live websites. Also if you don’t see any ads on the production website check the console to see if there are any errors.

Otherwise you will see ads just wait for google to connect properly.