How To Easily Integrate Adsense in NextJS with Route Switching (2024)

Shivam Bhalla
3 min readApr 30, 2024

--

It has been a painful experience trying to integrate ad sense with nextjs. I have tried several articles. I have been painfully trying to integrate it into my platform https://frontendlead.com/.

Lucky for you, I paid my dues and figured out the solution. Before I begin, I want to mention some things I have tried:

What I tried

Solution

Here is the solution I came up with, works across route changes and page load.

_app.tsx

<Script
async
src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${process.env.NEXT_PUBLIC_GOOGLE_ADS_CLIENT_ID}`}
strategy="lazyOnload"
crossOrigin="anonymous"
></Script>

_AdsBanner.tsx

import Router from "next/router";
import { useEffect } from "react";
declare global {
interface Window {
adsbygoogle: unknown[];
}
}

interface AdsBannerProps {
"data-ad-slot": string;
"data-ad-format": string;
"data-full-width-responsive": string;
"data-ad-layout"?: string;
}

const AdBanner = (props: AdsBannerProps) => {
useEffect(() => {
const handleRouteChange = () => {
const intervalId = setInterval(() => {
try {
// Check if the 'ins' element already has an ad in it
if (window.adsbygoogle) {
window.adsbygoogle.push({});
clearInterval(intervalId);
}
} catch (err) {
console.error("Error pushing ads: ", err);
clearInterval(intervalId); // Ensure we clear interval on errors too
}
}, 100);
return () => clearInterval(intervalId); // Clear interval on component unmount
};

// Run the function when the component mounts
handleRouteChange();

// Subscribe to route changes
if (typeof window !== "undefined") {
Router.events.on("routeChangeComplete", handleRouteChange);

// Unsubscribe from route changes when the component unmounts
return () => {
Router.events.off("routeChangeComplete", handleRouteChange);
};
}
}, []);

return (
<ins
className="adsbygoogle adbanner-customize mt-2"
style={{
display: "block",
overflow: "hidden",
border: process.env.NODE_ENV === "development" ? "1px solid red" : "none",
}}
data-adtest="on"
data-ad-client={process.env.NEXT_PUBLIC_GOOGLE_ADS_CLIENT_ID}
{...props}
/>
);
};
export default AdBanner;

Now call it.

YourComponent.tsx

import dynamic from "next/dynamic";
const AdBanner = dynamic(() => import("../Ads/AdsBanner"), {
ssr: false,
});

...
some render function

<AdBanner
data-ad-slot="slotnumber"
data-full-width-responsive="true"
data-ad-layout="in-article"
data-ad-format="fluid"
/>

Thats it! If you find this article helpful, consider upvoting it and checkout frontendlead.com, an all in one platform to help you prepare for frontend interviews.

Cheers.

Shivam

Bonus

  1. If you have an article that renders content from the server and you need fluid in article ads, like this article for instance: https://frontendlead.com/handbook/introduction, check out this article, where I explain how to implement it.
  2. If you want to test ads locally, check out how I do it here.

--

--