How to Add AdSense Auto Ads to Next.js and React
Integrating Google AdSense into a Single Page Application (SPA) like Next.js can be tricky. If done wrong, you will get hydration errors or the ads simply won't render on client-side navigation. Here is the correct way to do it in Next.js 16.
Hi, I'm Archit Karmakar. As a developer building tools like AdSense Checker AI, I often get asked by other devs how to properly insert AdSense into modern React frameworks. Let's look at the optimal approach using the Next.js `Script` component.
The Solution: Next.js Script Component
Google provides a single `<script>` tag for Auto Ads. You want this script to load efficiently without blocking your main thread. In the App Router (`app/layout.tsx`), you can use `next/script` to achieve this.
import Script from 'next/script'
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
<Script
id="adsense-init"
async
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXXXXXXXXXX"
crossOrigin="anonymous"
strategy="afterInteractive"
/>
</head>
<body>
{children}
</body>
</html>
)
}Key Things to Notice
- strategy="afterInteractive": This tells Next.js to inject the script immediately after the page becomes interactive. It won't block the initial HTML render, which is great for your Core Web Vitals.
- client=ca-pub-XXX: Remember to replace `ca-pub-XXXXXXXXXXXXXXXX` with your actual AdSense Publisher ID.
Handling Client-Side Routing
Auto Ads are smart enough to detect mutations in the DOM. However, if you are manually inserting specific Ad Units (display ads, in-feed ads) using a custom React component, you must call `(window.adsbygoogle = window.adsbygoogle || []).push()` inside a `useEffect` hook to force AdSense to render the ad on route changes.
'use client'
import { useEffect } from 'react'
export default function AdBanner() {
useEffect(() => {
try {
// @ts-ignore
(window.adsbygoogle = window.adsbygoogle || []).push({});
} catch (err) {
console.error(err);
}
}, []);
return (
<ins className="adsbygoogle"
style={{ display: 'block' }}
data-ad-client="ca-pub-XXXXXXXXXXXXXXXX"
data-ad-slot="1234567890"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
)
}Is your Next.js site fully compliant?
Even if the code is perfect, your content might still fail Google's review. Use our AI scanner to check your Next.js blog for content and SEO issues.
Conclusion
Adding AdSense to Next.js is straightforward if you leverage the built-in `<Script>` component. Avoid using standard HTML script tags to prevent hydration mismatches and performance bottlenecks.