Integrating Google AdSense with Next.js 14+ for Revenue Generation

November 14, 2024

5 min read

125 views

Google AdSense is one of the most popular advertising networks, enabling website owners to monetize their traffic by displaying targeted ads. In this guide, we’ll go through how to integrate Google AdSense with Next.js 14+, taking advantage of Next.js’s modern architecture for optimized ad performance and user experience.

Expected Outcomes

By the end of this 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 14+

Step 1: Prerequisites

Before you begin, make sure you have:

  • A Google AdSense Account: Sign up at Google AdSense.
  • Next.js 14+ Project: Ensure your project uses Next.js 14 or later.

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. Google adSense add site
  • Wait for Google to verify your site ownership and approve your account.

Create a GoogleAdSense Component

  • Create a reusable component to add AdSense scripts only in production. This ensures ads load only for live users, preserving development speed and resources.
tsx
// GoogleAdSense.tsx
 
import env from '@/lib/env';
import Script from 'next/script';
 
export const GoogleAdSense = () => {
  if (env.ENV !== 'production') {
    return null;
  }
 
  return (
    <Script
      async
      src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${env.NEXT_PUBLIC_ADSENSE_ID}`}
      crossOrigin="anonymous"
      strategy="afterInteractive"
    />
  );
};

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
// /app/layout.tsx
 
import './globals.css';
import { GoogleAdSense } from '@/components/GoogleAdSense';
 
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <head>
        <GoogleAdSense />
      </head>
      <body>{children}</body>
    </html>
  );
}

Step 3: Create a Reusable AdUnit Component

Now, let’s create a versatile AdUnit component that allows you to insert different types of ads throughout your site.

tsx
// AdUnit.tsx
 
'use client';
 
import { useEffect, useRef } from 'react';
 
interface AdUnitProps {
  adSlot: string;
  adFormat?: 'auto' | 'fluid' | 'rectangle' | 'horizontal' | 'vertical';
  style?: React.CSSProperties;
}
 
const formatStyles = {
  auto: { display: 'block' },
  fluid: { display: 'block' },
  rectangle: { display: 'inline-block', width: '300px', height: '250px' },
  horizontal: { display: 'inline-block', width: '728px', height: '90px' },
  vertical: { display: 'inline-block', width: '160px', height: '600px' },
};
 
export function AdUnit({ adSlot, adFormat = 'auto', style }: AdUnitProps) {
  const adRef = useRef<HTMLModElement>(null);
 
  useEffect(() => {
    try {
      const adsbygoogle = (window as any).adsbygoogle;
 
      if (adRef.current && adsbygoogle) {
        adsbygoogle.push({});
      }
    } catch (err) {
      console.error('AdSense error:', err);
    }
  }, []);
 
  return (
    <div className="ad-container my-4">
      <ins
        ref={adRef}
        className="adsbygoogle"
        style={{
          ...formatStyles[adFormat],
          ...style,
        }}
        data-ad-client="ca-pub-XXXXXXXXXXXXXXXX"
        data-ad-slot={adSlot}
        data-ad-format={adFormat}
        data-full-width-responsive="true"
      />
    </div>
  );
}

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 AdUnit Component

Here are examples of how to use the AdUnit 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
// /app/page.tsx
 
import { AdUnit } from '@/components/AdUnit';
 
export default function HomePage() {
  return (
    <main>
      {/* Above the fold */}
      <AdUnit adSlot="1234567890" adFormat="horizontal" style={{ marginBottom: '20px' }} />
 
      <section>
        <h1>Welcome to My Site</h1>
        <p>Explore the latest updates.</p>
      </section>
    </main>
  );
}
  • In-Article Ads: Insert ads within articles for natural engagement as users scroll through content.
tsx
export default function ArticlePage() {
  return (
    <article>
      <h2>Featured Article</h2>
      <p>Long-form content...</p>
 
      {/* In-article ad */}
      <AdUnit adSlot="1234567891" adFormat="rectangle" style={{ margin: '20px 0' }} />
 
      <p>More content...</p>
    </article>
  );
}
  • Responsive Sidebar Ads: Sidebar ads work well in blog or content-heavy layouts.
tsx
export default function Sidebar() {
  return (
    <aside>
      <h2>Related Content</h2>
      <AdUnit adSlot="1234567892" adFormat="vertical" style={{ marginTop: '20px' }} />
    </aside>
  );
}

Responsive Ads Example

To ensure your ads adjust to various screen sizes, set data-ad-format to auto, allowing AdSense to adapt the ad based on available space.

tsx
// Responsive Ad Example in HomePage.tsx
 
export default function HomePage() {
  return (
    <main>
      <AdUnit adSlot="1234567890" adFormat="auto" style={{ maxWidth: '100%' }} />
 
      <section>
        <h1>Welcome to My Site</h1>
        <p>Explore the latest updates.</p>
      </section>
    </main>
  );
}

Step 5: Testing and Troubleshooting

Test in Production

  • AdSense ads only render in production, so deploy your application and test ad placements and visibility.

Check for Errors

  • Use the browser console to check for any errors related to ad loading.

Best Practices for Ad Placement in Next.js 14+

  • Above the Fold: Place ads at the top of the page for visibility.
  • In-Content Ads: Position ads within content to improve engagement.
  • Limit Density: AdSense has ad density guidelines; avoid placing too many ads close together.

Revenue Optimization Tips

  • Optimize Core Web Vitals: Fast load times and responsive layouts improve both user experience and revenue.
  • Track Ad Performance: Regularly check your AdSense dashboard to monitor ad effectiveness and experiment with placements.

Frequently Asked Questions

  • Q: Why aren’t my ads showing on Next.js 14+?

    • A: Ensure you’ve completed site verification and deployed the 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 for any impacts.

With this guide, you’re ready to integrate Google AdSense into your Next.js 14+ application, creating a smooth user experience while effectively monetizing your site.


Similar articles