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 Next.js 15+. 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.
Expected Outcomes
By the end of this Google AdSense integration, you will have:
- Revenue Generation: Earn revenue from ads relevant to your content and audience.
- Enhanced Performance: Leverage Next.js’s client-server model for fast ad loading.
- Scalable Monetization: Set up a monetization strategy that grows with your site’s traffic.
How to Implement Google AdSense in Next.js 15+
Step 1: Prerequisites
Before you begin, make sure you have:
- A Google AdSense Account: First Sign up at Google AdSense.
- Next.js 15 or 14 Project: Ensure your project uses Next.js 14 or 15+.
Step 2: 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.
-
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.
.tsx
1
2// GoogleAdSense.tsx
3
4import env from '@/lib/env';
5import Script from 'next/script';
6
7export const GoogleAdSense = () => {
8if (env.ENV !== 'production') {
9 return null;
10}
11
12return (
13 <Script
14 async
15 src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${env.NEXT_PUBLIC_YOUR_ADSENSE_ID}`}
16 crossOrigin="anonymous"
17 strategy="afterInteractive"
18 />
19);
20};
21
22
Place the GoogleAdSense Component in Your Layout
- Include the
GoogleAdSense
component in your main layout file to load the AdSense script on all pages.
.tsx
1
2 // /app/layout.tsx
3
4import type { Metadata } from "next";
5import "./globals.css";
6import { GoogleAdSense } from "@/components/GoogleAdSense";
7
8export const metadata: Metadata = {
9title: "Create Next App",
10description: "Generated by create next app",
11};
12
13export default function RootLayout({
14children,
15}: Readonly<{
16children: React.ReactNode;
17}>) {
18return (
19 <html lang="en">
20 {/* Add it in the head of the file */}
21 <head>
22 <GoogleAdSense />
23 </head>
24 <body>{children}</body>
25 </html>
26
27);
28}
29
30
Step 3: Create a Reusable AdComponent
Now, let's create a versatile AdComponent
. This reusable component allows you to easily manage ad placements throughout your site.
.tsx
1
2// AdComponent.tsx
3
4"use client";
5import { useEffect, useRef } from "react";
6import Router from "next/router";
7interface AdUnitProps {
8adSlot: string;
9adFormat?: "auto" | "fluid" | "rectangle" | "horizontal" | "vertical";
10style?: React.CSSProperties;
11}
12
13const formatStyles = {
14auto: { display: "block" },
15fluid: { display: "block" },
16rectangle: { display: "inline-block", width: "300px", height: "250px" },
17horizontal: { display: "inline-block", width: "728px", height: "90px" },
18vertical: { display: "inline-block", width: "160px", height: "600px" },
19};
20
21declare global {
22interface Window {
23adsbygoogle: unknown[];
24}
25}
26export function AdUnit({ adSlot, adFormat = "auto", style }: AdUnitProps) {
27const adRef = useRef<HTMLModElement>(null);
28
29useEffect(() => {
30const handleRouteChange = () => {
31const intervalId = setInterval(() => {
32try {
33if (window.adsbygoogle) {
34window.adsbygoogle.push({});
35clearInterval(intervalId);
36}
37} catch (err) {
38if (process.env.NODE_ENV === "development") {
39console.error("Error pushing ads: ", err);
40}
41clearInterval(intervalId);
42}
43}, 100);
44return () => clearInterval(intervalId);
45};
46
47 handleRouteChange();
48
49 if (typeof window !== "undefined") {
50 Router.events.on("routeChangeComplete", handleRouteChange);
51
52 return () => {
53 Router.events.off("routeChangeComplete", handleRouteChange);
54 };
55 }
56
57}, []);
58
59return (
60
61<div className="ad-container my-4">
62<ins
63 ref={adRef}
64 className="adsbygoogle"
65 style={{
66 ...formatStyles[adFormat],
67 ...style,
68 }}
69 data-ad-client="ca-pub-XXXXXXXXXXXXXXXX" // Your Client ID
70 data-ad-slot={adSlot}
71 data-ad-format={adFormat}
72 data-full-width-responsive="true"
73/>
74</div>
75); }
76
77
adSlot: Unique identifier for each ad in your AdSense account.
adFormat: Format of the ad common values include auto
, rectangle
,horizontal
and vertical
.
Step 4: 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.
.tsx
1
2/
3// /app/page.tsx
4
5import { AdUnit } from '@/components/AdComponent';
6
7export default function MainPage() {
8return (
9<main>
10 {/* Above the fold */}
11 <AdUnit adSlot="1234567890" adFormat="horizontal" style={{ marginBottom: '20px' }} />
12
13 <section>
14 <h1>Welcome to My Site</h1>
15 <p>Explore the latest updates.</p>
16 </section>
17
18</main>
19);
20}
21
22
- In-Article Ads: Insert ads within articles for natural engagement as users scroll through content.
.tsx
1
2export default function ArticlePage() {
3return (
4
5<article>
6<h2>Featured Article</h2>
7<p>Long-form content...</p>
8
9 {/* In-article ad */}
10 <AdUnit adSlot="1234567891" adFormat="rectangle" style={{ margin: '20px 0' }} />
11
12 <p>More content...</p>
13 </article>
14
15);
16}
17
- Responsive Sidebar Ads: Sidebar ads work well in blog or content-heavy layouts.
.tsx
1export default function Sidebar() {
2return (
3 <aside>
4 <h2>Related Content</h2>
5 <AdUnit adSlot="1234567892" adFormat="vertical" style={{ marginTop: '20px' }} />
6 </aside>
7);
8}
- Responsive Ads Example: To ensure your ads adjust to various screen sizes, set
data-ad-format
toauto
, allowing AdSense to adapt the ad based on available space.
.tsx
1// Responsive Ad Example in HomePage.tsx
2
3export default function HomePage() {
4return (
5 <main>
6 <AdUnit adSlot="1234567890" adFormat="auto" style={{ maxWidth: '100%' }} />
7
8 <section>
9 <h1>Welcome to My Site</h1>
10 <p>Explore the latest updates.</p>
11 </section>
12 </main>
13);
14}
15
Step 5: 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+
- 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.
Revenue Optimization Tips
- Optimize Core Web Vitals: Fast load times and responsive layouts improve both user experience and revenue.
- Track Ad Performance: Regularly review your AdSense dashboard to monitor ad performance and experiment with different placements for optimal results.
Check also how to Add Google Analytics to Next.js and NextJs Seo Tips.
Frequently Asked Questions
-
Q: Why aren't my ads showing on Next.js Project?
A: Make sure you've completed site verification with Google AdSense and deployed your site in production mode.
-
Q: How can I make sure ads don't affect performance?
A: Load ads client-side only and monitor Core Web Vitals to ensure that Google AdSense ads don’t negatively impact performance
With this guide, you’re now ready to integrate Google AdSense into your Next.js application, ensuring a smooth user experience while effectively monetizing your site. By following the steps for Google AdSense integration and optimizing ad placements, you can maximize revenue and improve your site's performance.
If you found this blog helpful, feel free to share it with others who may benefit from it!