NextJS
How to Insert Google Adsense in Nextjs

How to Insert Manually Insert Google AdSense in NextJS

Google AdSense has automated insertion and you become eligible and enable it, but for a good positioning it asks for up to 90 days of testing and analysis. Realizing that are only 4 or 5 main routes for pages I decided to insert it manually.

Before you insert the ins tag and window code you must load the AdSense script once, doing this way:

import Script from 'next/script'
export default function AdSense() {
  return (
    <Script 
      id="google-adsense" 
      async 
      src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8251931233860363" 
      crossOrigin="anonymous" 
      strategy="afterInteractive"
    />
  )
}

You can call it at some page like /tutorial/page.tsx or at layout.tsx

export default async function RootLayout({ children }: { children: React.ReactNode }) {
 
  return(
    <html lang="en">
      <head>
        <AdSense />
      </head>
      <body>
        <main>
        </main>
      </body>
    </html>
  );
}

It gave some problems and erros but after all I got this result:

"use client";
 
import React, { useEffect } from "react";
 
interface AdSenseBannerProps {
    // Number give in AdSense Blocks site
  adSlot?: string;
    /*
        # adFormat
        "auto":	Responsive auto ad — let Google decide the size (most common).
        "fluid": For in-article or in-feed ads. Requires matching ad code.
        "rectangle": Fixed-size ad formats like 300x250 — usually not responsive.
    */
  adFormat?: "auto" | "fluid" | "rectangle";
 
    /*
        # adLayout
        "in-article": When using an in-article ad.
        "image-top": A layout style for in-feed.
        "": for auto ads or general use.
    */
  adLayout?: "in-article" | "image-top" | "";
 
  adResponsive?: "false" | "true"; //must be string
}
 
const AdSenseBanner: React.FC<AdSenseBannerProps> = ({
  adSlot = "1234567890", // Just the default adSlost as given from AdSense Blocks section, if you forget. Cannot be repeated.
  adFormat = "auto", // Google decides the size
  adLayout = "", // As defined in Google AdSense tool: "in-article" | "image-top" | "". "" if un sure
  adResponsive = "true"
}) => {
 
  useEffect(() => {
    try {
      if (window !== undefined) { // Prevent localhost errors. Window must be present
        // Like in Adsense Documentation: create or push in adsbygoogle object
        ((window as any).adsbygoogle = (window as any).adsbygoogle || []).push({});
      }
    } catch (e) { // Case something fails in window operations
      console.error('Error loading ads:', e);
    }
  }, [adSlot]); // As soon as adSlot is received
 
  return (
    <div key={`ad-${adSlot}`} className="my-6">
        {/* ins such as in Google AdSense Documentation */}
      <ins
        className="adsbygoogle"
        style={{
          display: "block",
          minHeight: "250px" // Assume some size
        }}
        data-ad-client="ca-pub-8251931233860363" // Same as defeined in <Script> tag
        data-ad-slot={adSlot} // Number give in AdSense Blocks site
        data-ad-format={adFormat}
        data-ad-layout={adLayout}
        data-full-width-responsive={adResponsive}
      />
    </div>
  );
};
 
export default AdsenseBanner;
 

How to apply inside other components

The Easiest part is to insert inside some page or any react component.

export default function Home() {
    return(
      <section>
        <div>Content X</div>
        <AdSenseBanner adSlot="2111111111">
        <div>Content Y</div>
        <div>Content Z</div>
        <AdSenseBanner adSlot="3111111111">
        <div>Content X</div>
        <div>Content Y</div>
        <AdSenseBanner adSlot="4111111111">
      </section>
    );
}
Last updated on