Hello Everyone So Today I am Gonna Talk About How to Run Google Ad sense, Google Ad sense Ad Units.
What is Problem
We Can Add Ad sense Code in head
tag of Nextjs13 App router but the Problem is faced for Google Ad sense Ad Units.
In New We have to Assign The our Ad Component as Client and The Ad Sense Ad Unit code Does Not Refresh On Page Changes.
Solution 1 For Auto Ads ( Follow This For Ad Units Also )
Firstly goto RootLayout which looks like below
<pre class="highlight tsx">```
<span class="k">export</span> <span class="k">default</span> <span class="kd">function</span> <span class="nx">RootLayout</span><span class="p">({</span>
<span class="nx">children</span><span class="p">,</span>
<span class="p">}:</span> <span class="p">{</span>
<span class="nl">children</span><span class="p">:</span> <span class="nx">React</span><span class="p">.</span><span class="nx">ReactNode</span><span class="p">;</span>
<span class="p">})</span> <span class="p">{</span>
<span class="k">return</span> <span class="p">(</span>
<span class="p"><</span><span class="nt">html</span> <span class="na">lang</span><span class="p">=</span><span class="s">'en'</span><span class="p">></span>
<span class="p"><</span><span class="nt">head</span><span class="p">></span>
<span class="p"></</span><span class="nt">head</span><span class="p">></span>
<span class="p"><</span><span class="nt">body</span> <span class="na">className</span><span class="p">=</span><span class="s">'bg-gray-100 font-sans'</span><span class="p">></span>
<span class="si">{</span><span class="nx">children</span><span class="si">}</span>
<span class="p"></</span><span class="nt">body</span><span class="p">></span>
<span class="p"></</span><span class="nt">html</span><span class="p">></span>
<span class="p">);</span>
<span class="p">}</span>
And You Got the Google Adsense Code Is Like Below
```
<script>async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1234567890123456" crossorigin/>
```
```
Now Convert the code to NextJs Script component
```
```
Script async
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1234567890123456"
crossOrigin="anonymous"
strategy='lazyOnload'
/>
```
```
Just add this in `head` tag and remember to strategy should be `lazyOnload` which have more chances of code running fine and also crossOrigin as anonymous.
### Solution 2 : Google Ad sense Ad Unit Codes In App Router
Now You Got The Code From Google Adsense Code Like This Below
```
```
async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1234567890123456" crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:inline-block;width:728px;height:90px"
data-ad-client="ca-pub-1234567890123456"
data-ad-slot="1234567890">
<script>
(window.adsbygoogle = window.adsbygoogle || []).push({});
</script>
now here the first part here the first script
is already rendered in head tag which we added in auto ads solution so we will just gonna go with remaining code.
After Converting it to NextJs Version It looks Like below
<pre class="highlight jsx">```
<span class="p"><</span><span class="nt">ins</span>
<span class="na">className</span><span class="p">=</span><span class="s">"adsbygoogle"</span>
<span class="na">style</span><span class="p">=</span><span class="si">{</span><span class="p">{</span> <span class="na">display</span><span class="p">:</span> <span class="dl">"</span><span class="s2">inline-block</span><span class="dl">"</span><span class="p">,</span> <span class="na">width</span><span class="p">:</span> <span class="mi">728</span><span class="p">,</span> <span class="na">height</span><span class="p">:</span> <span class="mi">90</span> <span class="p">}</span><span class="si">}</span>
<span class="na">data-ad-client</span><span class="p">=</span><span class="s">"ca-pub-1234567890123456"</span>
<span class="na">data-ad-slot</span><span class="p">=</span><span class="si">{</span><span class="mi">1234567890</span><span class="si">}</span>
<span class="p">/></span>
<span class="p"><</span><span class="nt">script</span> <span class="na">dangerouslySetInnerHTML</span><span class="p">=</span><span class="si">{</span><span class="p">{</span> <span class="na">__html</span><span class="p">:</span> <span class="s2">`(window.adsbygoogle = window.adsbygoogle || []).push({});`</span><span class="p">}</span><span class="si">}</span> <span class="p">/></span>
Now We Can Add This Code But it have issue of the We Have to Refresh the Page and then the Ad Loads and also does not load again on other pages due to smooth navigation of NextJS Built In.
For Resolving That We Have to Update Our Code Which Looks Complex But Completely Works.
First Create New `AdCode.jsx` File **It Should Be *jsx*** not `ts` or `tsx` because it have it's own error for typescript so do this.
First Add the Code in Class Component ( Don't Try to Add This in Function Component with useEffect() it works partially only ) Like Below this is complete file. we need to make our component client for client router we are gonna needed.
```
class AdCodeWithoutRouter extends React.Component {
renderAds() {
(window.adsbygoogle = window.adsbygoogle || []).push({});
}
componentDidMount() {
this.renderAds();
}
componentDidUpdate(prevProps) {
if (this.props.router.asPath !== prevProps.router.asPath) {
this.renderAds();
}
}
render() {
return (
<div className="container mx-auto text-center" aria-hidden={true}>
<ins
className="adsbygoogle"
style={{ display: 'block', width: '100%' }}
data-ad-client="ca-pub-1234567890"
data-ad-slot="123456"
data-ad-format="auto"
data-full-width-responsive="true"
>ins>
div>
);
}
}
```
```
Now We Also Need Some Imports and Function component After Modification Complete File Look Like Below. **useRouter is imported from 'next/navigation`** as per in nextjs13.
```jsx
'use client';
import React from 'react';
import { useRouter } from 'next/navigation';
class AdCodeWithoutRouter extends React.Component {
renderAds() {
(window.adsbygoogle = window.adsbygoogle || \[\]).push({});
}
componentDidMount() {
this.renderAds();
}
componentDidUpdate(prevProps) {
if (this.props.router.asPath !== prevProps.router.asPath) {
this.renderAds();
}
}
render() {
return (
className="adsbygoogle"
style={{ display: 'block', width: '100%' }}
data-ad-client="ca-pub-1234567890"
data-ad-slot="123456"
data-ad-format="auto"
data-full-width-responsive="true"
>
);
}
} const AdCode= () => {
const router = useRouter();
return ;
};
export default AdCode;
{% raw %}
```
```
here what is happening that when `componentDidMount` is ran when component is loaded for first time and it is rerendered on navigating to new pages because of `componentDidUpdate` method of Class Component.
Now I Know Many of you will try to make this in `useEffect` and Pure Single Functional Component. I tried and Failed to get what i actually wanted.
But If anybody Succeed Please Inform in the Comments maybe that helps this code to less complex.
Now you can use the Ad-code Component Wherever you want.
Bye.
```
```
Comments (0)