Next.js

Next.jsにGoogle Adsenseを貼る方法

Next.jsにGoogle Adsenseを貼る方法をメモ。

Adsenseのコード

AdSenseの管理画面から発行できるタグの例。
こやつをNext.js上で next/link 等を加味して発火させねばならない。

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxx"
     crossorigin="anonymous"></script>
<!-- xxx -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-xxx"
     data-ad-slot="xxx"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>

Next.jsにAdsenseのコードを追加する

headでadsbygoogle.jsを読み込み

/pages/_document.tsxを修正して、<Head>内で adsbygoogle.js を読み込む

{/* GoogleAdsenseの広告タグを発火させるのは本番のみ */}
{process.env.NODE_ENV === 'production' && (
  <Script
    async
    src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxxxxxxx"
    crossOrigin="anonymous"
    strategy="afterInteractive"
  />
)}

Adsenseを表示するコンポーネントを作成する

  • https://github.com/scttcper/react-adsense/blob/master/src/adsense.tsx の実装が参考になる
  • GoogleAdsenseProps は使いたい広告で可変になることに注意
  • <div key={asPath}> にしておかないと、NextLinkの移動のときに広告が変わらなくなってしまう
import { useRouter } from 'next/router';
import { useEffect } from 'react';

const PUBLISHER_ID = 'xxxxxxxxxxxx';

type GoogleAdsenseProps = {
  slot: string;
  style?: React.CSSProperties;
  format?: string;
  responsive?: string;
};

export const GoogleAdsense = ({
  slot,
  style = { display: 'block' },
  format,
  responsive = 'false',
}: GoogleAdsenseProps): JSX.Element => {
  const { asPath } = useRouter();

  useEffect(() => {
    try {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      ((window as any).adsbygoogle = (window as any).adsbygoogle || []).push(
        {},
      );
    } catch (error) {
      // Pass
    }
  }, [asPath]);

  return (
    <div key={asPath}>
      <ins
        className="adsbygoogle"
        style={style}
        data-adtest={process.env.NODE_ENV === 'production' ? 'off' : 'on'}
        data-ad-client={`ca-pub-${PUBLISHER_ID}`}
        data-ad-slot={slot}
        data-ad-format={format}
        data-full-width-responsive={responsive}
      />
    </div>
  );
};

広告を貼りたい場所で作成したコンポーネントを呼ぶ

<GoogleAdsense
  slot="xxxxxxx"
  style={{ display: 'block' }}
  format="auto"
  responsive="true"
/>

-Next.js