Oteto Blogのロゴ

【Next.js】SPAにGoogle AdSenseを導入する

やりたいこと

Next.js製のサイトにGoogle AdSense広告を導入したい。あわよくば開発環境でも本番環境と同様に表示させたい。

解決法

1. パプリッシャーIDとスロットIDを取得

Google Adsenseの管理画面から「広告」メニューを選択し、挿入したい広告ユニット(無ければ新規作成する)の列の「コードを取得」をクリックする。

<script
  async
  src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxx"
  crossorigin="anonymous"
></script>
<!-- <広告名> -->
<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>

するとHTMLが吐かれるので、この中から下記2つのIDを取得しておく

  • パプリッシャーID(ca-pub-xxx
  • スロットID(data-ad-slot="xxx"

2. scriptコンポーネント作成

import Script from "next/script";

const ScriptGad = () => {
  return (
    <Script
      async
      src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=<パプリッシャーID>"
      crossOrigin="anonymous"
    />
  );
};

export default ScriptGad;

先ほど取得したパプリッシャーIDを用いてGoogle Adsenseのscriptを読み込むコンポーネントを作成。

next/scriptを使うことで<link rel="preload">の挿入やbody閉じタグ付近への配置をしてくれるなど、勝手に第三者コードが最適化される。

const Layout = async ({ children }: { children: React.ReactNode }) => {
  return (
    <html lang="ja">
      <body>
        <main>{children}</main>
        <ScriptGad />
      </body>
    </html>
  );
};

export default Layout;

あとは各ページ共通のレイアウト部分に配置する。

3. 広告本体のコンポーネント作成

"use client";

import { useEffect } from "react";
import { usePathname } from "next/navigation";

const GadBlock = () => {
  const pathname = usePathname();

  useEffect(() => {
    try {
      ((window as any).adsbygoogle = (window as any).adsbygoogle || []).push(
        {}
      );
    } catch (e) {
      console.error(e);
    }
  }, [pathname]);

  return (
    <div>
      <ins
        className="adsbygoogle"
        style={{ display: "block" }}
        data-adtest={process.env.NODE_ENV === "development" ? "on" : "off"}
        data-ad-client="<パプリッシャーID>"
        data-ad-slot="<スロットID>"
        data-ad-format="auto"
        data-full-width-responsive="true"
      />
    </div>
  );
};

export default GadBlock;

Adsense広告本体を表示するコンポーネントを作成する。

  • insタグの属性は基本的に管理画面から取得した通りに指定
    • localhostでも広告が表示されるよう、開発環境の時はdata-adtest"on"にする
  • usePathnameを利用しページ遷移時に(adsbygoogle = window.adsbygoogle || []).push({});を毎回実行

あとは広告を表示したい箇所でこのGadBlockコンポーネントを呼び出せばOK。

4. 開発環境のホスト名を変更

localhostでも広告を変更させるためにローカルの設定を変更する必要があるが、下記の方法で実現できる。 Google Adsense広告をlocalhost(ローカル環境)で表示する