Ad code & integration

How to add Google AdSense to a Next.js App Router site

Last updated Published By the editorial team6 min5 sources

Key takeaways

  • In the Next.js App Router, a next/script tag in the root layout loads the AdSense library once for all routes, and Next.js guarantees it loads only once across navigations.
  • The default afterInteractive strategy injects the script client-side after some hydration, while beforeInteractive injects it into the initial HTML head.
  • Ad units need a Client Component that renders the ins element and calls adsbygoogle.push in useEffect, because pushing touches window.
  • Next.js forwards extra attributes such as nonce and crossOrigin from the Script component to the final script element.
  • Static files in the public folder, such as public/ads.txt, are served from the site root.
Firefox web browser window displaying a Wikipedia page
Image: Firefox web browser on wikipedia page,Mozilla Corporation,CC BY-SA 4.0,via Wikimedia Commons.

In a Next.js App Router project, load the AdSense code once from the root layout with next/script, render each ad unit from a small Client Component that pushes to adsbygoogle in useEffect, and put ads.txt in public/. The part most tutorials miss is navigation: layouts persist across routes, so a slot in a layout needs a new <ins> element per route before it can request a new ad.

What changes compared with a normal HTML site?

Google’s instructions are written for static HTML: the AdSense code goes in <head>, ad unit code goes in <body> where the ad should appear (Where to place ad unit code in your HTML). In the App Router you have three differences to deal with:

  1. Inline <script> tags inside React components are not executed the way they are in plain HTML, so the per-unit push call has to move into JavaScript that runs after render.
  2. Client-side navigation does not reload the document. The library stays loaded, layouts stay mounted, and only the changed segments re-render.
  3. Server Components cannot touch window, so the push must live in a Client Component ('use client').

The code below targets the current App Router (Next.js 16 at the time of writing). It uses ca-pub-0000000000000000 and slot 1234567890 as placeholders.

How do I load the AdSense script in the root layout?

The Next.js scripts guide shows third-party scripts placed in the root layout to load for all routes, and states that “Next.js will ensure the script will only load once, even if a user navigates between multiple pages”.

// app/layout.tsx
import Script from 'next/script'

const adsEnabled = process.env.NODE_ENV === 'production'

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>{children}</body>
      {adsEnabled && (
        <Script
          async
          src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-0000000000000000"
          crossOrigin="anonymous"
          strategy="afterInteractive"
        />
      )}
    </html>
  )
}

Next.js forwards attributes it does not use itself (such as crossOrigin or nonce) to the final <script> element, as the scripts guide explains under “Additional Attributes”.

Which strategy fits AdSense?

Strategy What the Script reference says Fit for AdSense
beforeInteractive Injected into the initial HTML head, downloaded before Next.js code; must be in the root layout; for critical scripts Works, but competes with your own code for early bandwidth
afterInteractive (default) Injected client-side, loads after some hydration; suggested for tag managers and analytics Good default
lazyOnload Injected during browser idle time after all resources are fetched Delays every ad request; ads above the fold appear late
worker Experimental, “does not yet work with the App Router” Do not use

One consequence of afterInteractive: the script is not in the server-rendered HTML. If you plan to connect your site to AdSense with the code snippet method, the review crawler may not see it. Use the ads.txt or meta tag method instead, as described in connecting a site to AdSense, or switch to beforeInteractive.

You may also see this console warning: “AdSense head tag doesn’t support data-nscript attribute.” next/script adds data-nscript to the tag, and the AdSense library logs a warning for data attributes it does not recognize on its head tag. It is a warning only.

How do I build an ad unit Client Component?

// app/components/AdUnit.tsx
'use client'

import { useEffect, useRef } from 'react'
import { usePathname } from 'next/navigation'

declare global {
  interface Window {
    adsbygoogle: unknown[]
  }
}

type Props = { adSlot: string; minHeight?: number }

export default function AdUnit({ adSlot, minHeight = 280 }: Props) {
  const pathname = usePathname()
  const pushedFor = useRef<string | null>(null)

  useEffect(() => {
    if (pushedFor.current === pathname) return
    pushedFor.current = pathname
    try {
      ;(window.adsbygoogle = window.adsbygoogle || []).push({})
    } catch (err) {
      console.error(err)
    }
  }, [pathname])

  return (
    <div style={{ minHeight }}>
      <ins
        key={pathname}
        className="adsbygoogle"
        style={{ display: 'block' }}
        data-ad-client="ca-pub-0000000000000000"
        data-ad-slot={adSlot}
        data-ad-format="auto"
        data-full-width-responsive="true"
      />
    </div>
  )
}

How it works:

  • usePathname returns the current path (usePathname reference), and the docs show it used with useEffect to “do something in response to a route change”.
  • key={pathname} makes React replace the <ins> with a fresh element whenever the route changes. A filled <ins> cannot be filled again; the library logs “All ‘ins’ elements in the DOM with class=adsbygoogle already have ads in them.” if you push without a new empty slot.
  • The pushedFor ref prevents a second push for the same route. That matters in development, where React Strict Mode runs effects twice.
  • The wrapper’s minHeight reserves space so the ad does not shift content. Tune it to your layout; see reserving space for ads.
  • In a page (not a layout), the component unmounts and remounts on navigation anyway; the key is what makes it work in persistent layouts such as a sidebar.

Use it from any Server Component:

// app/blog/[slug]/page.tsx
import AdUnit from '@/app/components/AdUnit'

export default async function Post() {
  return (
    <article>
      <h1>Post title</h1>
      <p>Intro...</p>
      <AdUnit adSlot="1234567890" />
      <p>Body...</p>
    </article>
  )
}

Requesting a new ad after a user navigates to new content is different from refreshing ads on a timer. The ad placement policies forbid refreshing “a page or an element of a page without the user requesting a refresh”, so never re-push on an interval, on scroll or on tab focus.

What about Auto ads in a Next.js app?

With the root layout script in place, turning on Auto ads in AdSense is enough for the first page view. Google does not document how Auto ads behave across client-side route changes in a framework router, so do not assume they re-analyze each route. The single-page apps guide discusses the options, including full page loads for selected links. In Next.js, a plain <a> element instead of <Link> gives you a full page load for that link.

How do I add a CSP nonce?

If your site uses a nonce-based Content Security Policy, Next.js documents generating a fresh nonce per request in proxy.ts, passing it through an x-nonce request header and reading it in a Server Component (Next.js CSP guide):

// app/layout.tsx (excerpt)
import { headers } from 'next/headers'
import Script from 'next/script'

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  const nonce = (await headers()).get('x-nonce') ?? undefined
  return (
    <html lang="en">
      <body>{children}</body>
      <Script
        async
        src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-0000000000000000"
        crossOrigin="anonymous"
        nonce={nonce}
      />
    </html>
  )
}

The Next.js docs warn that nonces require dynamic rendering: static pages are generated at build time, when no request exists to create a nonce. The directives the AdSense code itself needs are covered in CSP for AdSense.

Where does ads.txt go?

Create public/ads.txt. Next.js serves files in public from the root URL, so it is available at /ads.txt:

google.com, pub-0000000000000000, DIRECT, f08c47fec0942fa0

Check it on the production domain after deploy. A proxy.ts matcher or a rewrite that catches every path can accidentally intercept it.

Troubleshooting

Symptom Cause Fix
“adsbygoogle.push() error: All ‘ins’ elements … already have ads in them.” More pushes than empty slots (Strict Mode double effect, duplicate components) Guard with a ref, push once per new <ins>
Ad blank after navigating, other pages fine Slot in a persistent layout keeps its filled <ins> Add key={pathname} to the <ins>
“No slot size for availableWidth=0” The container had no width when the push ran (hidden tab, collapsed accordion, display:none) Push only when the slot is visible and laid out
Ads in development No environment guard Check NODE_ENV or your own flag before rendering

Keep the ad code itself as Google provides it: same script URL, same <ins> attributes, same push call. The AdSense code modification policy permits changes for a clean user experience and responsive sizing, not changes that alter how ads are delivered.

Frequently asked questions

Which next/script strategy should I use for AdSense?

The default, afterInteractive, is a sensible choice: Next.js describes it as loading early but after some hydration, which suits tag managers and analytics. beforeInteractive puts the script in the initial HTML head but is meant for critical scripts such as consent managers. lazyOnload waits for browser idle time and delays every ad request. The worker strategy is experimental and does not work with the App Router.

Why do I see "AdSense head tag doesn't support data-nscript attribute" in the console?

next/script adds a data-nscript attribute to the script it renders. The AdSense library reads data- attributes on its head tag as settings, finds one it does not know and logs a warning. It is a console warning, not an error, and ads still load. If you want a clean console, render a plain script tag in the root layout head instead.

Why does my ad stay blank after a client-side navigation in Next.js?

If the ad component lives in a layout that persists across routes, the same ins element stays in the DOM and is already filled, so nothing new is requested. Give the ins a key based on usePathname so React creates a new element on navigation, then push once for that new element in useEffect.

Can I use AdSense on statically exported Next.js pages?

Yes. The ad code runs in the browser, so static export works. The exception is a Content Security Policy with nonces: Next.js only injects nonces on dynamically rendered pages, because static pages have no request to generate a nonce from.

Sources

  1. Script Component · Next.js Docs
  2. How to load and optimize scripts · Next.js Docs
  3. usePathname · Next.js Docs
  4. How to set a Content Security Policy (CSP) for your Next.js application · Next.js Docs
  5. Where to place ad unit code in your HTML · Google AdSense Help