Coder Social home page Coder Social logo

nextjs-google-adsense's Introduction

Nextjs Google AdSense

Structure of this package is based on nextjs-google-analytics. Credits to @MauricioRobayo.

Google AdSense for Next.js

This package optimizes script loading using Next.js Script tag, which means that it will only work on apps using Next.js >= 11.0.0.

Installation

npm install --save nextjs-google-adsense
# or
yarn add nextjs-google-adsense

Initializing AdSense

Add the GoogleAdSense component with the publisherId prop set to your Publisher ID (optained from Google Adsense panel) to your custom App file:

// pages/_app.js
import { GoogleAdSense } from "nextjs-google-adsense";

const App = ({ Component, pageProps }) => {
  return (
    <>
      <GoogleAdSense publisherId="pub-XXXXXXXXXXXXXXXX" />
      <Component {...pageProps} />
    </>
  );
};

export default App;

You can also add the publisherId as environment variable as NEXT_PUBLIC_ADSENSE_PUBLISHER_ID. The environment variable will override the prop if both are set.

This component will inject the script for AdSense units to be rendered with Next.js's Script afterInteractive strategy.

Usage

You can use automatic placements by Google AdSense or add manual ad units using this package.

Auto Ads (Recommended)

After initializing the AdSense, most effective way for ad unit placements is Auto Ads. Gives the best results for most use cases. Let Google's $B AI do the placement.

In order to activate Auto Ads, you need to login your Google AdSense panel and enable it for the particular domain name you are using for your Next.js project.

Google AdSense Panel > Ads (Sidebar) > By site (Tab) > Press Edit icon for your domain > Ad Settings > Expand Auto Ads and enable it > Enable Optimize exiting units

Additionally, options like Anchor ads and Side rails can be managed under "Ad Formats" accordion menu and you don't need to make any changes in your Next.js project for it.

Note that, Auto Ads might take a while to show up, and optimize itself depending on user behaviour.

Manual Ad Unit Placement

In order to place ads manually, use <ResponsiveAdUnit /> in any of your pages/ files or components.

Create a new Display ad unit;

Google AdSense Panel > Ads (Sidebar) > By ad unit (Tab) > Display ads > Name your unit, Choose "Responsive" > Create

// pages/index.js (or any component)
import { ResponsiveAdUnit } from "nextjs-google-adsense";

export default function Home() {
  return (
    <>
      <h1>My Home Page</h1>
      <p>Welcome to my homepage. This is hero text</p>

      <ResponsiveAdUnit
        publisherId="pub-XXXXXXXXXXXXXXXX"
        slotId="XXXXXXXXXX"
        type="after-home-hero"/>

      <p>This is my home page content</p>
      <p>Way more content here</p>

      <ResponsiveAdUnit
        publisherId="pub-XXXXXXXXXXXXXXXX"
        slotId="XXXXXXXXXX"
        type="end-of-homepage"/>
    </>
  );
};

export default Home;

Copy your data-ad-slot="XXXXXXXXXX" value into the component as slotId prop. You can omit publisherId if you defined NEXT_PUBLIC_ADSENSE_PUBLISHER_ID environment variable. The environment variable will override the prop if both are set.

The ad unit automatically gets re-rendered when the route changes. The type prop id used as key when there are multiple ad units in the page addition to the current router.asPath string. You can add a slug defining the unit's position on the page in order to differentiate a unit from others. Additionally you can re-render the ad unit by changing type prop after page load.

ResponsiveAdUnit also accepts style prop.

// TODO: Add "fixed" unit type, passing it for now since it is not prefered a lot.

Debugging your Google AdSense

// TODO: Add some steps here in order to debug it, feel free to PR. (Use gtag console and debug={true} prop for <GoogleAdSense/>)

Notes

Ignore AdSense head tag doesn't support data-nscript attribute. warning.

Contributing

Contributions, issues and feature requests are welcome!

Show your support

Give a โญ๏ธ if you like this project!

LICENSE

This software and maintainers are not affiliated with Google AdSense, Next.js or Vercel. And authors offer no warranties.

MIT

nextjs-google-adsense's People

Contributors

btk avatar soranoo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

soranoo anhgeeky

nextjs-google-adsense's Issues

How can I use this package for nextjs 13

I try to use this package on my new nextjs 13, but it looks like doesn't work, would you please give me the instruction that how to use it on nextjs 13 project?

Uncaught errors and empty page when loading additional content in JS with Ad Slots on the same page

Hello I've integrated your module and it works fine until I tried to lazy load some blocks on my app, adding blocks with ResponsiveAdUnit loaded in ReactJS I've got the following errors :
"Uncaught TagError: adsbygoogle.push() error: All ins elements in the DOM with class=adsbygoogle already have ads in them." error
image
image
I think it's due to the init of the library
I've found this that is exactly the same : https://stackoverflow.com/questions/74577652/how-to-solve-uncaught-tagerror-adsbygoogle-push-error-all-ins-elements-in-t
someone is suggesting but it did not worked for me in the main app js
if (adsbygoogle && !adsbygoogle.loaded) (adsbygoogle = (window as any).adsbygoogle || []).push({});

Reinitiate/reload ads on page change

Hey,

I was wondering how you're handling page changes so that the ads get reinitiated/readjusted to the layout changes.

For example, on the adsense dashboard, I excluded the index and contact page to NOT contain any ads. When I visit example.com/ this works just as expected, but when I visit some other blog post first, and then use next.js's client-side router to change the route to the index page example.com/, the ads just remain in the "blog layout" as if the window location never actually changed. This breaks the whole page layout of the newly navigated-to page.

I saw something like this to "reload" ads on page changes online, but it seems to do absolutely nothing in my case:

  const router = useRouter();


  useEffect(() => {
    if ((window as any).adsbygoogle) {
      const adsC = document.getElementsByClassName("adsbygoogle").length;
      for (let i = 0; i < adsC; i++) {
        try {
          ((window as any).adsbygoogle =
            (window as any).adsbygoogle || []).push({});
        } catch (e) {}
      }
    }
    return () => {
      if ((window as any).adsbygoogle) {
        const adsC = document.getElementsByClassName("adsbygoogle").length;
        for (let i = 0; i < adsC; i++) {
          try {
            ((window as any).adsbygoogle =
              (window as any).adsbygoogle || []).push({});
          } catch (e) {}
        }
      }
    };
  }, [router, router.pathname]);

I see you do something similar for ResponsiveAdUnit.tsx, but what about the auto ads spread all around the pages?

Thanks ๐Ÿ™‚

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.