Adding AdSense to a Next.js App Router site takes four pieces: a client component that loads adsbygoogle.js once, an ad unit component that pushes each <ins> slot exactly once, a google-adsense-account meta tag so Google can verify the site, and an ads.txt file. Pasting Google's snippet into the root layout works, but it's the slowest way to do it. The ad script then competes with your own JavaScript while the page loads, and Auto ads can push content around while the visitor starts reading.
The approach below is the one this site runs in production. The AdSense script doesn't load until the visitor first scrolls, taps, presses a key or moves the mouse. Every slot reserves its space up front, and ad units are plain client components that cope with App Router navigation. I'll go through each piece, then cover what happens on route changes, which is where most App Router AdSense code breaks.
Store the publisher ID in an environment variable
Your publisher ID is the ca-pub- value in your AdSense account (Account, then Settings, then Account information). Put it in .env.local and in your host's environment settings:
NEXT_PUBLIC_GOOGLE_ADSENSE_ID=ca-pub-0000000000000000It needs the NEXT_PUBLIC_ prefix because the ad components read it in the browser. Next.js inlines NEXT_PUBLIC_ values at build time, so set it before next build, not only at runtime. If you build in Docker, that means passing it as a build argument. The ID isn't a secret (it's in every page that shows an ad), but keeping it out of the code lets a staging build run with no ads at all, because every component below renders nothing when the variable is empty.
Load adsbygoogle.js on the first interaction
Here's the loader. It's a client component that renders nothing. On mount it listens for the first scroll, pointer, key, touch or wheel event, and only then adds the AdSense script to the page:
'use client'
import { useEffect } from 'react'
const ADSENSE_ID = process.env.NEXT_PUBLIC_GOOGLE_ADSENSE_ID
const EVENTS = ['scroll', 'pointerdown', 'pointermove', 'keydown', 'touchstart', 'wheel'] as const
export function GoogleAdSense() {
useEffect(() => {
if (process.env.NODE_ENV !== 'production' || !ADSENSE_ID) return
const load = () => {
EVENTS.forEach((event) => window.removeEventListener(event, load))
if (document.querySelector('script[data-adsense-loader]')) return
const script = document.createElement('script')
script.async = true
script.crossOrigin = 'anonymous'
script.src = `https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${ADSENSE_ID}`
script.dataset.adsenseLoader = ''
document.head.appendChild(script)
}
EVENTS.forEach((event) => window.addEventListener(event, load, { once: true, passive: true }))
return () => EVENTS.forEach((event) => window.removeEventListener(event, load))
}, [])
return null
}The data-adsense-loader attribute and the check before appending stop a second script being added if the effect ever runs twice. The once: true listeners plus the explicit removal mean whichever event fires first wins and the rest are dropped. The NODE_ENV check keeps ads out of next dev. You can't get real ads on localhost anyway, and it saves you from clicking your own units by accident.
Why not next/script?
next/script is the right tool for most third-party scripts, but none of its strategies waits for the user. The Next.js Script component reference lists four. beforeInteractive loads before hydration and belongs to bot detectors and consent managers. afterInteractive, the default, loads right after hydration. lazyOnload waits for browser idle time after the page's resources have loaded. worker is experimental and doesn't work in the App Router. Even lazyOnload runs the ad script shortly after the load event, which is still inside the window where lab tools measure Total Blocking Time and layout shift. A plain useEffect that waits for an event is the only way to push it past the first interaction.
Why loading on interaction helps Core Web Vitals, and what it costs
AdSense is a large script that pulls in more scripts and iframes. Loaded during page load, it takes main-thread time from your own hydration, which shows up as Total Blocking Time in Lighthouse and can make early clicks feel slow (Interaction to Next Paint). If you use Auto ads, the script also inserts ads into the page as soon as it runs, and every insertion above the visitor's reading position is a layout shift. Waiting for the first interaction moves all of that off the critical path. The page paints, hydrates and becomes responsive with nothing but your code running. web.dev's guide to loading ads without hurting page speed gives the same advice in general form: load ad scripts asynchronously, defer what isn't critical, and reserve space for every slot.
Be honest with yourself about what the lab numbers mean, though. Lighthouse and PageSpeed's lab test don't scroll, tap or type, so the ad script never loads in that test, and your lab score will look better than what a real visitor gets. Field data (the Core Web Vitals report in Search Console, or CrUX) is what counts. A real visitor still downloads the script a second or two in. You've moved the cost to a moment when it hurts less, not made it disappear.
The trade-off is that ads appear slightly later. The first ad request waits for an interaction, so a slot is empty for a moment after the visitor starts scrolling, and a visitor who opens the page and never touches it never sees an ad. That's usually a small loss, because people who don't scroll rarely look at ads either, but measure it against your own AdSense reports before and after the change. If you rely heavily on Auto ads, be aware that they'll now appear after the visitor has started reading, which is exactly when an inserted ad moves content under them. Manual units with reserved space, like the ones below, avoid that.
AdSense's rules on modifying the ad code don't mention delayed loading either way. The script URL and the <ins> markup here are exactly what Google gives you; only the moment they load changes. If your account depends on it, read the current policy pages yourself.
Verify the site with the google-adsense-account meta tag
There's one side effect to deal with. AdSense verifies a new site by looking for its code on your home page, and with the loader above, the script isn't in the HTML Google fetches. Use the documented alternative: a meta tag in the <head>. The AdSense help page on adding and verifying a site gives its form as <meta name="google-adsense-account" content="ca-pub-…">. The Metadata API renders it through the other field, and the root layout is also where the loader goes:
import type { Metadata } from 'next'
import type { ReactNode } from 'react'
import { GoogleAdSense } from '@/components/adsense/google-adsense'
import './globals.css'
const adsenseId = process.env.NEXT_PUBLIC_GOOGLE_ADSENSE_ID
export const metadata: Metadata = {
title: 'My site',
...(adsenseId ? { other: { 'google-adsense-account': adsenseId } } : {}),
}
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>
{children}
<GoogleAdSense />
</body>
</html>
)
}The root layout persists across client-side navigation, so GoogleAdSense mounts once per page load and its listeners never re-register. View the page source after a production build and you'll see <meta name="google-adsense-account" content="ca-pub-…"/> in the head, and no adsbygoogle.js script until you interact with the page.
An ad unit component that reserves its space
Each ad slot is an <ins class="adsbygoogle"> element plus one call to adsbygoogle.push({}), which asks AdSense to fill the next empty slot. In React that call belongs in an effect, and it has to run exactly once per element:
'use client'
import { useEffect, useRef, type CSSProperties } from 'react'
type AdFormat = 'auto' | 'rectangle' | 'horizontal' | 'vertical'
interface AdUnitProps {
adSlot: string
adFormat?: AdFormat
}
declare global {
interface Window {
adsbygoogle: unknown[]
}
}
const ADSENSE_ID = process.env.NEXT_PUBLIC_GOOGLE_ADSENSE_ID
// Each format reserves its box before the ad arrives, so nothing below it moves.
const formatStyles: Record<AdFormat, CSSProperties> = {
auto: { display: 'block', minHeight: '280px' },
rectangle: { display: 'block', width: '300px', height: '250px', margin: '0 auto' },
horizontal: { display: 'block', width: '100%', maxWidth: '728px', height: '90px', margin: '0 auto' },
vertical: { display: 'block', width: '160px', height: '600px', margin: '0 auto' },
}
export function AdUnit({ adSlot, adFormat = 'auto' }: AdUnitProps) {
const pushedRef = useRef(false)
useEffect(() => {
// One push per <ins>. Strict Mode and routes that are shown again run this
// effect a second time, and AdSense throws if an <ins> is filled twice.
if (pushedRef.current) return
pushedRef.current = true
try {
;(window.adsbygoogle = window.adsbygoogle || []).push({})
} catch (err) {
console.error('AdSense push failed', err)
}
}, [])
if (!ADSENSE_ID) return null
return (
<ins
className="adsbygoogle"
style={formatStyles[adFormat]}
data-ad-client={ADSENSE_ID}
data-ad-slot={adSlot}
data-ad-format={adFormat}
data-full-width-responsive="true"
/>
)
}The (window.adsbygoogle = window.adsbygoogle || []).push({}) line is Google's own pattern, and it's what makes loading on interaction work. Before the script arrives, window.adsbygoogle is a plain array and each push just adds an entry to the queue. When adsbygoogle.js loads, it processes everything already queued and fills those slots. Units can mount long before the script exists and nothing is lost.
The pushedRef guard matters. AdSense throws a TagError ("All 'ins' elements in the DOM with class=adsbygoogle already have ads in them") when you push for an element that's already filled. React Strict Mode runs effects twice in development, and, as we'll see, the App Router can run them again when a page comes back. The ref survives both, so each element gets one push.
The formatStyles map is the layout shift fix. AdSense injects its iframe after hydration, so a slot with no size collapses to zero height and then jumps open when the ad arrives, shoving everything below it down the page. Giving every format an explicit width and height (or a minHeight for responsive units) means the box exists in the server-rendered HTML and the ad fills it without moving anything. The margin: '0 auto' centres fixed-width units, which as block elements would otherwise sit flush left.
Serve a different unit per breakpoint without hiding one
A 728×90 leaderboard doesn't fit on a phone, so you'll want a 300×250 rectangle on mobile. The obvious approach is to render both and hide one with a CSS class. Don't. AdSense still processes the hidden <ins>, finds no width, and logs an availableWidth=0 error for a slot that never fills. Mount exactly one unit instead:
'use client'
import { useEffect, useState } from 'react'
import { AdUnit } from './ad-unit'
const DESKTOP_QUERY = '(min-width: 768px)'
function useMediaQuery(query: string): boolean | null {
const [matches, setMatches] = useState<boolean | null>(null)
useEffect(() => {
const media = window.matchMedia(query)
const update = () => setMatches(media.matches)
update()
media.addEventListener('change', update)
return () => media.removeEventListener('change', update)
}, [query])
return matches
}
export function ResponsiveAdUnit({ desktopSlot, mobileSlot }: { desktopSlot: string; mobileSlot: string }) {
const isDesktop = useMediaQuery(DESKTOP_QUERY)
if (isDesktop === null) {
// Same boxes as the two real units, switched by CSS, so swapping one in moves nothing.
return <div className="mx-auto h-[250px] w-[300px] md:h-[90px] md:w-full md:max-w-[728px]" />
}
return isDesktop ? (
<AdUnit adSlot={desktopSlot} adFormat="horizontal" />
) : (
<AdUnit adSlot={mobileSlot} adFormat="rectangle" />
)
}The server doesn't know the viewport, so until the effect runs the component renders a placeholder. The placeholder's size comes from CSS breakpoints, not JavaScript, so it already matches the unit that will replace it at either width. Reserving the taller box at every width and letting the real unit shrink it would still count as a layout shift, because a box getting smaller moves content just as much as one getting bigger. The placeholder classes are Tailwind's, which create-next-app sets up by default; with plain CSS, use a media query with the same two sizes.
Using the components is ordinary JSX. Put units in pages or in components that pages render:
import type { ReactNode } from 'react'
import { AdUnit } from '@/components/adsense/ad-unit'
import { ResponsiveAdUnit } from '@/components/adsense/responsive-ad-unit'
export function ArticleWithAds({ title, children }: { title: string; children: ReactNode }) {
return (
<div className="mx-auto flex max-w-6xl flex-col gap-10 lg:flex-row">
<article className="min-w-0 flex-1">
<h1>{title}</h1>
{children}
<ResponsiveAdUnit desktopSlot="1234567890" mobileSlot="2345678901" />
</article>
<aside className="lg:w-[300px]">
<AdUnit adSlot="2345678901" adFormat="rectangle" />
</aside>
</div>
)
}Notice the sidebar isn't hidden on mobile. A hidden lg:block on the aside would reproduce the zero-width problem. If you don't want a sidebar ad on small screens, don't render the unit there at all.
What happens to ads on App Router route changes?
Client-side navigation is where AdSense code written for the Pages Router breaks. The App Router has no next/router events; the Next.js useRouter reference says router.events has been replaced, and the supported way to react to a URL change is usePathname (with useSearchParams if the query matters) in an effect. You don't need either here, because the components above react to mounting, not to the URL. Here's what happens on each kind of navigation, and I checked each case in a production build.
The root layout and the loader stay mounted, so the script loads once per document. Moving from one page to another unmounts the old page's units and mounts new ones; each new <ins> pushes once and gets a fresh ad. That's true even between two URLs of the same dynamic route, such as /post/first and /post/second, because Next.js treats a different param value as a different page. A unit inside a layout.tsx, on the other hand, stays mounted while you move between the pages under that layout, so it keeps the ad it already has. If you want a new ad per page view, put the unit in the page, not the layout.
Cache Components changes one detail. New apps from create-next-app enable it by default, and with it Next.js doesn't unmount the page you leave. It hides it with React's <Activity> (the DOM stays, with display: none), cleans up its effects, and runs them again if you come back. The cacheComponents reference describes this. For ads, that means a filled <ins> survives in a hidden page and the push effect runs a second time on return, which is why the pushedRef guard exists: the returning page shows the ad it already had instead of throwing a TagError. It's also why the component doesn't force a fresh <ins> on every URL change by keying it on usePathname(). A hidden page would render a new, empty slot while hidden, and AdSense could pick that zero-width slot up on the next push.
I couldn't load real ads locally, because AdSense only fills slots on sites that are added and approved in your account. So the route-change behaviour was checked in a throwaway App Router app with Playwright, against a stub that mimics how adsbygoogle.js drains its queue and fills the next empty slot. In that run, with Cache Components on and off, no slot was pushed twice, nothing landed in a hidden slot, and every visible slot was filled after each navigation. Treat that as a test of the React side only, and confirm the real thing in production with the browser console open.
Add ads.txt
The last piece is ads.txt, a plain text file that lists who's authorised to sell your ad inventory. AdSense still serves ads without one, but it flags the missing file in your account until it's in place, and the file is what stops anyone else selling your inventory as theirs. In Next.js it's a static file, so put it in public/ and it's served at /ads.txt:
google.com, pub-0000000000000000, DIRECT, f08c47fec0942fa0Use your own publisher ID without the ca- prefix; the last field, f08c47fec0942fa0, is Google's certification authority ID and stays the same for everyone. The AdSense ads.txt guide has the exact line for your account, and it notes that changes can take a few days to show up in AdSense (up to a month on low-traffic sites). The file must be at the root of the domain that shows the ads, so if a proxy or redirect sits in front of Next.js, check https://your-domain/ads.txt returns the file as text/plain and not your 404 page.
Once it's deployed, open a page in a normal browser window, scroll once, and check three things in DevTools: one request to adsbygoogle.js in the Network tab, no TagError or availableWidth=0 messages in the console, and each <ins> carrying data-adsbygoogle-status="done" after AdSense processes it. Then click a link to another page and check again.













