Tech Verse Logo
Enable dark mode
Integrating Google AdSense with the Latest Next.js App Router

Integrating Google AdSense with the Latest Next.js App Router

Tech Verse Daily

Tech Verse Daily

4 min read

Google AdSense is a popular way to earn money by showing ads on your website. In this guide, we will show you how to add Google AdSense to the Next.js 15 app router. You'll learn the easy steps for Google AdSense integration and how to set up ads in your Next.js project. This Next.js AdSense setup will help you start earning revenue quickly and efficiently.

Initial Setup and Verification

After setting up your AdSense account, follow these steps to add your site and verify ownership.

Add Your Site to Google AdSense

  • Sign in to AdSense, go to Site Management, and add your website.

    Google AdSense add site
  • Wait for Google to verify your site ownership and approve your account.

Create a GoogleAdSense Component

  • Create a reusable Google AdSense component that loads ads only in production. This ensures ads are shown to live users while improving development speed and conserving resources.

import env from '@/lib/env';
import Script from 'next/script';

export const GoogleAdSense = () => {
if (env.ENV !== 'production') {
  return null;
}

return (
  <Script
    async
    src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${env.NEXT_PUBLIC_YOUR_ADSENSE_ID}`}
    crossOrigin="anonymous"
    strategy="afterInteractive"
  />
);
};

Place the GoogleAdSense Component in Your Layout

  • Include the GoogleAdSense component in your main layout file to load the AdSense script on all pages.

import type { Metadata } from "next";
import "./globals.css";
import { GoogleAdSense } from "@/components/GoogleAdSense";

export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};

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

);
}

Create a Reusable AdComponent

Now, let's create a versatile AdComponent. This reusable component allows you to easily manage ad placements throughout your site.

"use client";
import { useEffect, useRef } from "react";
import Router from "next/router";
interface AdUnitProps {
adSlot: string;
adFormat?: "auto" | "fluid" | "rectangle" | "horizontal" | "vertical";
style?: React.CSSProperties;
}

const formatStyles = {
auto: { display: "block" },
fluid: { display: "block" },
rectangle: { display: "inline-block", width: "300px", height: "250px" },
horizontal: { display: "inline-block", width: "728px", height: "90px" },
vertical: { display: "inline-block", width: "160px", height: "600px" },
};

declare global {
interface Window {
adsbygoogle: unknown[];
}
}
export function AdUnit({ adSlot, adFormat = "auto", style }: AdUnitProps) {
const adRef = useRef<HTMLModElement>(null);

useEffect(() => {
const handleRouteChange = () => {
const intervalId = setInterval(() => {
try {
if (window.adsbygoogle) {
window.adsbygoogle.push({});
clearInterval(intervalId);
}
} catch (err) {
if (process.env.NODE_ENV === "development") {
console.error("Error pushing ads: ", err);
}
clearInterval(intervalId);
}
}, 100);
return () => clearInterval(intervalId);
};

  handleRouteChange();

  if (typeof window !== "undefined") {
    Router.events.on("routeChangeComplete", handleRouteChange);

    return () => {
      Router.events.off("routeChangeComplete", handleRouteChange);
    };
  }

}, []);

return (

<div className="ad-container my-4">
<ins
  ref={adRef}
  className="adsbygoogle"
  style={{
    ...formatStyles[adFormat],
    ...style,
  }}
  data-ad-client="ca-pub-XXXXXXXXXXXXXXXX" // Your Client ID
  data-ad-slot={adSlot}
  data-ad-format={adFormat}
  data-full-width-responsive="true"
/>
</div>
); }

adSlot: Unique identifier for each ad in your AdSense account.
adFormat: Format of the ad. Common values include auto, rectangle,horizontal and vertical.

Using the Reusable AdComponent

Here are examples of how to use the AdComponent component in various sections of your Next.js app:

  • Above the Fold (Top of the Page): Placing ads above the fold increases visibility and click-through rates.

import { AdUnit } from '@/components/AdComponent';

export default function MainPage() {
return (
<main>
  {/* Above the fold */}
  <AdUnit adSlot="1234567890" adFormat="horizontal" style={{ marginBottom: '20px' }} />

  <section>
    <h1>Welcome to My Site</h1>
    <p>Explore the latest updates.</p>
  </section>

</main>
);
}
  • In-Article Ads: Insert ads within articles for natural engagement as users scroll through content.


export default function ArticlePage() {
return (

<article>
<h2>Featured Article</h2>
<p>Long-form content...</p>
    <AdUnit adSlot="1234567891" adFormat="rectangle" style={{ margin: '20px 0' }} />
    <p>More content...</p>
  </article>

);
}
  • Responsive Sidebar Ads: Sidebar ads work well in blog or content-heavy layouts.

export default function Sidebar() {
return (
  <aside>
    <h2>Related Content</h2>
    <AdUnit adSlot="1234567892" adFormat="vertical" style={{ marginTop: '20px' }} />
  </aside>
);
}
  • Responsive Ads Example: To ensure your ads adjust to various screen sizes, set data-ad-format to auto, allowing AdSense to adapt the ad based on available space.

export default function HomePage() {
return (
  <main>
    <AdUnit adSlot="1234567890" adFormat="auto" style={{ maxWidth: '100%' }} />

    <section>
      <h1>Welcome to My Site</h1>
      <p>Explore the latest updates.</p>
    </section>
  </main>
);
}

Testing and Troubleshooting

Test in Production

  • Google AdSense ads only render in production, so deploy your application and test ad placements and visibility.

Check for Google AdSense Errors

  • Use the browser console to check for any errors related to ad loading.This helps ensure that ads are properly displayed and functioning on your website.

Best Practices for Google AdSense Placement in Next.js 15+ App Router

  • Above the Fold: Fast load times and responsive layouts improve both user experience and revenue.

  • In-Content Ads: Position ads within the content to boost user engagement and improve ad performance.

  • Limit Density: Follow AdSense ad density guidelines and avoid placing too many ads too close together, ensuring a smooth user experience.