Skip to content

fix: add pathname based refresh to GoogleAdSense #18#26

Merged
soranoo merged 1 commit intobetafrom
fix-auto-ad-no-show-when-neg
Oct 10, 2025
Merged

fix: add pathname based refresh to GoogleAdSense #18#26
soranoo merged 1 commit intobetafrom
fix-auto-ad-no-show-when-neg

Conversation

@soranoo
Copy link
Copy Markdown
Owner

@soranoo soranoo commented Oct 10, 2025

Summary by Sourcery

Bug Fixes:

  • Ensure the AdSense script rerenders when the pathname changes to refresh ads after navigation

Summary by CodeRabbit

  • Bug Fixes
    • Resolved an issue where ads did not reliably reload after in-app navigation.
    • Ads now refresh on each route change, improving relevance, visibility, and fill rates.
    • Reduces occurrences of blank ad spaces and eliminates the need for manual page refresh to see updated ads.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Oct 10, 2025

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

This PR enhances the GoogleAdSense component to reload the AdSense script whenever the Next.js route changes by capturing the current pathname and incorporating it into the Script component’s key.

Sequence diagram for AdSense script reload on route change

sequenceDiagram
    participant NextRouter
    participant GoogleAdSense
    participant Script
    NextRouter->>GoogleAdSense: Route changes (pathname updates)
    GoogleAdSense->>Script: Rerender with new key (includes pathname)
    Script->>Browser: Loads AdSense script for new page
Loading

Class diagram for updated GoogleAdSense component

classDiagram
    class GoogleAdSense {
        +GoogleAdSenseProps props
        +debug: boolean
        +publisherId: string
        +pathname: string
        +_publisherId: string
        +JSX.Element | null
    }
    GoogleAdSense : usePathname()
    GoogleAdSense : Script (key includes pathname)
Loading

File-Level Changes

Change Details Files
Enable route-based refresh for the AdSense script
  • Add usePathname hook to retrieve the current route
  • Include pathname in the Script component’s key to trigger rerender
  • Add inline comment explaining the purpose of the key change
src/GoogleAdSense.tsx

Possibly linked issues

  • #123: The PR adds a key to the Google AdSense script component, incorporating the pathname to force a re-render and ensure ads load correctly upon page navigation, directly addressing the issue of ads not displaying on route changes.
  • Fixed README.md Incorrect Example #1: The PR adds a pathname-based refresh to the GoogleAdSense script, ensuring auto ads refresh on route change, directly addressing the issue.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes - here's some feedback:

  • Add a use client directive at the top of this file since you’re using the usePathname hook in a client component.
  • Don’t forget to import usePathname from next/navigation to avoid a reference error.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Add a `use client` directive at the top of this file since you’re using the `usePathname` hook in a client component.
- Don’t forget to import `usePathname` from `next/navigation` to avoid a reference error.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Oct 10, 2025

Walkthrough

Added Next.js pathname awareness to GoogleAdSense by importing usePathname and incorporating it into the Script element’s key so the ad script remounts on route changes. No public APIs or exports were altered.

Changes

Cohort / File(s) Summary of edits
Ad rendering keyed by route
src/GoogleAdSense.tsx
Imported usePathname; captured pathname inside component; updated Script key to include _publisherId and pathname to force remount on navigation; added comment about rerender behavior.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Router as Next.js Router
  participant GA as GoogleAdSense
  participant Script as Next Script (AdSense)

  Router->>GA: Render component (initial route)
  GA->>Script: Render with key = _publisherId + pathname
  Note right of Script: Script mounts for current route

  Router-->>GA: Route change (pathname updated)
  GA->>Script: Render with new key (_publisherId + new pathname)
  Note right of Script: Previous Script unmounts<br/>New Script mounts for new route
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

I hop between paths, click-click, new scene,
Ads remount swiftly, tidy and clean.
A key with a route—now that’s the trick,
Scripts blink away, then bounce back quick.
On every hop my carrots align,
Pages change, and placements shine. 🥕✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title clearly and concisely summarizes the primary change—adding pathname‐based refresh logic to the GoogleAdSense component—matching the modifications in the PR and referencing the relevant issue.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-auto-ad-no-show-when-neg

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@soranoo soranoo changed the title fix: add pathname based refresh to GoogleAdSense fix: add pathname based refresh to GoogleAdSense #18 Oct 10, 2025
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3e29f0a and 61a984b.

📒 Files selected for processing (1)
  • src/GoogleAdSense.tsx (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Sourcery review
🔇 Additional comments (1)
src/GoogleAdSense.tsx (1)

38-39: Implementation looks correct, pending critical fix.

The key construction properly includes the pathname to trigger remount on navigation. The explanatory comment is helpful for maintainability. Once the missing "use client" directive is added and the approach is verified, this implementation should work as intended.

Comment thread src/GoogleAdSense.tsx
// ref: https://github.com/btk/nextjs-google-adsense/blob/master/src/components/GoogleAdSense.tsx
// ref: https://medium.com/frontendweb/how-to-add-google-adsense-in-your-nextjs-89e439f74de3

import { usePathname } from "next/navigation";
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Critical: Add "use client" directive.

usePathname() is a client-side hook that requires this component to be a Client Component. Without the "use client" directive at the top of the file, this will throw a runtime error in Next.js App Router.

Apply this diff to add the required directive:

+
+'use client';
+
 // ref: https://github.com/btk/nextjs-google-adsense/blob/master/src/components/GoogleAdSense.tsx
 // ref: https://medium.com/frontendweb/how-to-add-google-adsense-in-your-nextjs-89e439f74de3
🤖 Prompt for AI Agents
In src/GoogleAdSense.tsx around line 4, the component uses the client-side hook
usePathname() but the file is missing the "use client" directive; add a single
line containing "use client" as the very first line of the file (before any
imports) so the component is treated as a Client Component and the usePathname()
hook can run without runtime errors.

Comment thread src/GoogleAdSense.tsx
debug = false,
...props
}: GoogleAdSenseProps): JSX.Element | null => {
const pathname = usePathname();
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

🧩 Analysis chain

Verify that remounting the script is the optimal approach.

While this implementation correctly triggers a remount on route changes, consider whether this is the best approach for AdSense. Remounting the script on every navigation may:

  • Re-download and re-execute the script unnecessarily
  • Cause flickering or layout shifts
  • Impact page load performance

Please verify whether Google AdSense recommends this approach for SPAs, or if programmatic ad refresh (e.g., using adsbygoogle.push()) would be more performant.


🌐 Web query:

What is the recommended approach for refreshing Google AdSense ads on route changes in Next.js applications? Should the script be remounted or should ads be refreshed programmatically?

💡 Result:

Short answer: load the ad script once and refresh ad slots programmatically on route changes — don’t repeatedly remount the script tag.

Why: Google’s publisher APIs provide refresh/clear methods (e.g., googletag.pubads().refresh()) or, for classic AdSense ad units, calling (adsbygoogle = window.adsbygoogle || []).push({}) for each unit after navigation. Remounting the global script on every route can cause race conditions and duplicate loads; programmatic refresh follows Google best practices (also avoid refreshing too frequently and only refresh viewable slots). [1][2][3]

References:

  • Google Publisher Tag — control ad loading & refresh (best practices, refresh() usage and limits). [1]
  • Community guidance / Next.js examples recommending loading the script once and refreshing slots (Stack Overflow). [2][3]

Refresh AdSense slots programmatically instead of remounting the script

Load the ad script once (e.g., in _app.tsx or src/GoogleAdSense.tsx without key={pathname}), then on each route change call (window.adsbygoogle = window.adsbygoogle || []).push({}) or googletag.pubads().refresh() per Google’s best practices. Avoid duplicate script loads, race conditions, and layout shifts.

@soranoo soranoo changed the base branch from main to beta October 10, 2025 18:29
@soranoo soranoo merged commit a8518a2 into beta Oct 10, 2025
4 checks passed
@soranoo soranoo deleted the fix-auto-ad-no-show-when-neg branch October 10, 2025 18:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant