@sachithrrra

Published on

How to setup Adsense in NextJS

This is a simple guide on how to implement Google Adsense on your NextJS app. In order to implement Adsense, you need to get approved first.

Table of Contents

Installing Adsense code

First you must copy the code from Adsense website. Then this code should be placed in Head tag of the website.

<script
async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-607**********769"
crossorigin="anonymous">
</script>

We must make some changes to this code in order to add this to a NextJS app.

<Script
   id="Adsense-id"
   data-ad-client="ca-pub-607**********769"
   async={true}
   strategy="beforeInteractive"
   src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
   crossOrigin="anonymous"
/>

Add the above code to the _app.js file.

import Script from "next/script";
import { Layout } from "../components/Layout";
import "../styles/globals.css";

function MyApp({ Component, pageProps }) {

  return (
    <Layout>
      <GoogleAnalytics />
      <Script
        id="Adsense-id"
        data-ad-client="ca-pub-607**********769"
        async={true}
        strategy="beforeInteractive"
        src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
        crossOrigin="anonymous"
      />
      <Component {...pageProps} />
      <Analytics />
    </Layout>
  );
}

export default MyApp;

Creating ad component

The next step is creating the Ad component and adding indiviual ad codes.

You will get a code like this once you create an ad unit in Adsense dashboard.

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

Let's modify this code and add it to a seperate component in NextJS.

import { useRouter } from "next/router";
import { useEffect } from "react";

export function GoogleAd() {

  useEffect(() => {
    window.onload = function () {
      (adsbygoogle = window.adsbygoogle || []).push({});
    };
  }, []);
  return (
    <div
      className="adparent"
      style={{
        minwidth: "320px",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        overflow: "hidden",
      }}
    >
      <ins
        className="adsbygoogle"
        style={{ display: "block" }}
        data-ad-client="ca-pub-607**********769"
        data-ad-slot="7018265229"
        data-ad-format="auto"
        data-full-width-responsive="true"
      ></ins>
    </div>
  );
}

Now you can place this component anywhere you need to display Adsense ads.