Published on Monday 20 May 2024
Tags: adsense1
[SOLVED] Adsense Not Working On NextJS 13 Blog
How to fix Adsense not showing on a NextJS 13 blog using the app Router.
After a lot of searching, I finally discovered why Adsense wasn't working on my NextJS 13 blog (using the app Router, not the page Router).
First, ensure your domain is verified (approval status ready) and that the ads.txt file is available at the root domain (ads.txt status authorized). Check these before proceeding.
For auto ads, Google provided this code:
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8705050524972624"
crossorigin="anonymous"></script>
Initially, I converted it to this and placed it in head.tsx
, which is included in the root layout.tsx
as <Head />
right before the body tag:
<Script
async
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXXXXXXXXXX"
crossOrigin="anonymous"
strategy="lazyOnload"
/>
However, no ads appeared, and the script tag didn't show up when inspecting the page source.
The issue was the "strategy". Changing the value from lazyOnload
to afterInteractive
solved the problem:
<Script
async
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXXXXXXXXXX"
crossOrigin="anonymous"
strategy="afterInteractive"
/>
Switching from lazyOnload
(which defers the script loading until after the page and all resources are fully loaded) to afterInteractive
(which loads and executes the script as soon as the main content is interactive) made the Adsense script load earlier, ensuring it was ready to display ads correctly.
Further Considerations: Async or Defer?
While not essential to solve the problem, choosing between async
and defer
attributes for script tags depends on how you want your scripts to interact with the HTML loading process.
- Async: The script is fetched asynchronously and executed as soon as it's available. Use this for independent scripts like analytics or advertising scripts that don't rely on the DOM being fully parsed.
- Defer: The script is fetched asynchronously but executed only after the HTML document is fully parsed. Use this for scripts that manipulate the DOM or depend on the full HTML structure being loaded.
For Adsense scripts, using defer
(achieved via strategy="afterInteractive"
in Next.js) is typically more appropriate because:
- Execution Order: Ensures the script executes after the HTML parsing is complete, aiding proper ad rendering.
- Performance: Balances performance and functionality by loading the script asynchronously but deferring its execution to avoid blocking HTML parsing.
Therefore, the final code is:
<Script
defer
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXXXXXXXXXX"
crossOrigin="anonymous"
strategy="afterInteractive"
/>