Menu

Google AdSense Integration

Google AdSense lets you display ads on your website and earn revenue. AdSense integration usually has two parts:

  • AdSense side: apply for AdSense, add your site, pass review, create ad units
  • Code side: inject the AdSense script, (optional) render ad slots, verify ads are showing

Prerequisites

  • Your site is deployed to production
  • Your site has real content and required pages (e.g. About / Privacy / Terms) to improve your approval rate

Step 1: Apply and add your site

  1. Open AdSense: https://www.google.com/adsense/
  2. Sign up / sign in and submit your site URL
Submit your site

Step 2: Verify ownership and configure environment variables

  1. Follow the instructions to verify site ownership
  2. Copy the part after ca-pub- and paste it into NEXT_PUBLIC_GOOGLE_ADSENSE_ID
.env
NEXT_PUBLIC_GOOGLE_ADSENSE_ID=xxxxxxxxxxxx
Site verification guide
  1. Paste the provided ads.txt content into public/ads.txt
ads.txt guide

Step 3: Choose “Auto ads” or “Ad units”

Option A: Auto ads

Enable Auto ads in the AdSense dashboard and Google will automatically place ads on your site.

If you’ve completed the steps above, this should work without any additional code.

Option B: Manual ad slots

If you want ads to appear in specific places, create an ad unit and render an ad slot in your page.

A common approach is to create an AdSlot component:

"use client";
 
import { useEffect } from "react";
 
type AdSlotProps = {
  adSlot: string;
  adFormat?: string;
  fullWidthResponsive?: boolean;
};
 
export function AdSlot({
  adSlot,
  adFormat = "auto",
  fullWidthResponsive = true,
}: AdSlotProps) {
  const client = process.env.NEXT_PUBLIC_GOOGLE_ADSENSE_ID;
 
  useEffect(() => {
    try {
      // @ts-expect-error adsbygoogle is injected by AdSense
      (window.adsbygoogle = window.adsbygoogle || []).push({});
    } catch {
      // ignore
    }
  }, []);
 
  if (!client) return null;
 
  return (
    <ins
      className="adsbygoogle"
      style={{ display: "block" }}
      data-ad-client={client}
      data-ad-slot={adSlot}
      data-ad-format={adFormat}
      data-full-width-responsive={fullWidthResponsive ? "true" : "false"}
    />
  );
}

Set adSlot to the data-ad-slot value generated in the AdSense dashboard, then render <AdSlot /> where you want the ad to appear.