programming
How to Put Ads on Your Website
Steps detailing how to put advertisements on your website to earn money from content
21st December 2021
·
1 Min Read
Follow these steps to put advertisements on your React/NextJs website.
Create an adsense account
Go to https://www.google.com/adsense/start/ and create an account. Once you have created an account go to Sites on the sidebar and click on Add Site. Once you add the site it needs to be reviewed. It says it to allow them 14 days to review your site but in my experience it takes a day or two.
Set up ad on site
Environment variables
Go to google adsense. Click Ads on the side bar and then click By ad unit. Here you can create how you want your ad to look like. Once you're done you will get a code snippet. Items of note are data-ad-client and data-ad-slot.
Go to your .env file and save it as such.
1# .env
2
3NEXT_PUBLIC_AD_CLIENT="INSERT DATA-AD-CLIENT HERE"
4NEXT_PUBLIC_AD_SLOT="INSERT DATA-AD-SLOT HERE"
Set up code
Add ads script
Insert this script in between the <body></body> tags of your pages. In NextJs I put it in between my body tags in _document.tsx.
1// /pages/_document.tsx
2
3<script
4 async
5 src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${process.env.NEXT_PUBLIC_AD_CLIENT}`}
6 crossOrigin="anonymous"
7 />
Set up component
I created a component called AdBanner so it was easier to integrate it into my site. The adtest parameter is used to indicate that a request for ads is a test. Remember to set it as 'off' for production.
1// /components/AdBanner.tsx
2
3export interface IWindow {
4 adsbygoogle?: any;
5}
6
7declare const window: IWindow;
8
9export const AdBanner = () => {
10 useEffect(() => {
11 try {
12 (window.adsbygoogle = window.adsbygoogle || []).push({});
13 } catch (err) {
14 console.log(err);
15 }
16 }, []);
17
18 return (
19 <ins
20 className="adsbygoogle block"
21 data-ad-client={process.env.NEXT_PUBLIC_AD_CLIENT}
22 data-ad-slot={process.env.NEXT_PUBLIC_AD_SLOT}
23 data-ad-format="auto"
24 data-full-width-responsive="true"
25 data-adtest={process.env.NEXT_PUBLIC_VERCEL_ENV === 'production' ? 'off' : 'on'}
26 />
27 );
28};
Things to note
Adsense crawlers reject localhost. That is why ads wont render in localhost and will show as whitespace.
Please disable adblock
References:
Tags: