How To Implement Adsense With Server Driven Articles Using NextJS [2024]

Shivam Bhalla
2 min readApr 30, 2024

--

If you are anything like me, you probably ran into a lot of issues trying to integrate google ad sense with Nextjs, with route changes. It’s especially difficult to integrate inside articles, when the data comes from the server. In this article, I will show you how can integrate adsense fluid ads inside articles seamlessly.

As a prerequisite, I recommend checking out my first article, that teaches you how to integrate Adsense with NextJS: https://medium.com/@shivambh28/how-to-easily-integrate-adsense-in-nextjs-with-route-switching-2024-1ded88699231

Now lets move onto article based ads.

Generally speaking, given the article data will be coming from the server, such as Wordpress, you will want to dangerously set the server data into a div and render your article, like this:

<div dangerouslySetInnerHTML={{
__html: articleContent,
}}
/>

So how do you get your ads to appear within the articleContent? The idea is, after the second paragraph of your article, append a div with id of `ad-banner-placeholder` and then use a hook to place your ad component inside of it. Like this:

useEffect(() => {
// Split the content into paragraphs
const paragraphs = contentCloned.split("\n");

// Insert the AdBanner placeholder after the second paragraph
if (paragraphs.length > 2) {
paragraphs.splice(2, 0, '<div id="ad-banner-placeholder"></div>');
}

// Join the paragraphs back together into a single string
contentCloned = paragraphs.join("\n");
setArticleConent(contentCloned);
}, [articleContent]);

Then utilizing ReactDOM, you can append it to the div.

import { createPortal, render } from "react-dom"
useEffect(() => {
const adPlaceholder = document.getElementById("ad-banner-placeholder");
if (adPlaceholder) {
const AdBannerElement = (
<AdBanner
data-ad-slot="3346579334"
data-full-width-responsive="true"
data-ad-layout="in-article"
data-ad-format="fluid"
/>
);

render(AdBannerElement, adPlaceholder);
}
}, [contentCloned]);

That’s about it. If you find this helpful, consider upvoting it! Also check out frontendlead.com, an all in one platform to help you prepare for frontend interviews.

Cheers!

Shivam

--

--