@sachithrrra

Published on

How to setup Adsense in NextJS 13

Implementing Google Adsense in Your Next.js 13 App

Table of Contents

Getting Started with Adsense

Before integrating Adsense into your Next.js application, it's essential to obtain approval from Google Adsense. Once you've been approved, follow these steps to implement the ads:

1. Installing the Adsense Code

  • Copy the Adsense code: Begin by copying the provided code snippet from your Adsense account.

  • Modify for Next.js 13: Make the following adjustments to the code to ensure compatibility with Next.js 13:

    <Script
      async={true}
      src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-ca-pub-607**********769"
      strategy="lazyOnload"
      crossOrigin="anonymous"
    />
    
  • Add to layout.tsx: Place this modified code within your layout.tsx file, as illustrated below:

    import Script from 'next/script'
    import './globals.css'
    
    export default async function RootLayout({ children }: { children: React.ReactNode }) {
      return (
        <html lang="en">
          <body>
            {children}
            {/* Adsense code */}
            <Script
              async={true}
              src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-ca-pub-607**********769"
              strategy="lazyOnload"
              crossOrigin="anonymous"
            />
          </body>
        </html>
      )
    }
    

2. Creating the Ad Component

  • Obtain ad unit code: Generate an ad unit within your Adsense dashboard to receive a unique ad code snippet.

  • Adapt for Next.js: Create a dedicated component named AdCode.tsx to manage individual ad codes, incorporating the following modifications:

    'use client'
    import { usePathname } from 'next/navigation'
    import React, { useEffect } from 'react'
    
    interface AdCodeProps {
      adSlot: string;
    }
    
    const AdCode: React.FC<AdCodeProps> = ({ adSlot }) => {
      const pathName = usePathname()
    
      useEffect(() => {
        if (window.adsbygoogle) {
          ;(window.adsbygoogle = window.adsbygoogle || []).push({})
        }
      }, [pathName])
    
      return (
        <div className="flex w-full" aria-hidden={true}>
          <ins
            className="adsbygoogle"
            style={{ display: 'block', width: '100%' }}
            data-ad-client="ca-pub-607**********769"
            data-ad-slot={adSlot}
            data-ad-format="auto"
            data-full-width-responsive="true"
          ></ins>
          <script
            dangerouslySetInnerHTML={{
              __html: '(window.adsbygoogle = window.adsbygoogle || []).push({});',
            }}
          ></script>
        </div>
      )
    }
    
    export default AdCode
    

3. Utilizing the Ad Component

  • Import and use: Import the AdCode component into any page where you intend to display ads, providing the relevant ad slot as a prop:

    'use client';
    import AdCode from '@/components/AdCode';
    import Button from '@/components/ui/button';
    
    export default function HomePage() {
      return (
        <div className="flex flex-col items-center justify-center gap-4">
          <p className="w-full text-lg text-center font-medium cursor-pointer pb-10 px-6">
            Adsense code will be displayed below
          </p>
          <AdCode adSlot={'4270980247'}/>
        </div>
    

Known issues:

Known Issues

- TagError: adsbygoogle.push() error: All 'ins' elements in the DOM with class=adsbygoogle already have ads in them.

This error has been observed, but the ads are loading and displaying as expected. The cause of this error is yet to be determined, and a solution is still being searched.