0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[microCMS] Next.js で作成したフロント側にGoogleアドセンスを設置する

0
Posted at

microCMSを利用したサイトにads.txtを設置し、Googleアドセンスのタグを入れる方法です。

やりたいこと

Googleアドセンスをサイトに入れたい。

事前準備

Next.js でよく使われるサードパーティーのライブラリが配布されているのでインストールします。

npm install @next/third-parties@latest next@latest

ads.txt の設置

Gogoleアドセンスから発行される、パブリッシャー ID(pub-0000000000000000)の入ったファイルになります。

google.com, pub-0000000000000000, DIRECT, f08c47fec0942fa0

ads.txt はサイトのルートディレクトリにアップロードする必要があります。
直接設置もしくはフロント側で環境変数を参照にして生成したものを設置します。

環境変数を利用した例

番環境とステージング、ローカルでコンテナを分けたり、タグそのものを出力しないようできます。
環境変数は .evn などで指定してください。

ADSENSE_ADS_TXT_CONTENT="google.com, pub-0000000000000000, DIRECT, f08c47fec0942fa0"
// app/ads.txt/route.ts
import { NextResponse } from 'next/server';

export async function GET() {
  const content = process.env.ADSENSE_ADS_TXT_CONTENT;

  // 環境変数がない場合(開発環境など)は404エラーを返す
  if (!content) {
    return new NextResponse('Not Found', { status: 404 });
  }

  // 本番環境(環境変数がある場合)はプレーンテキストとして内容を返す
  return new NextResponse(content, {
    headers: {
      'Content-Type': 'text/plain; charset=utf-8',
    },
  });
}

アドセンスのタグを設置

配布されているテンプレートを例にします。

オリジナル

追加した部分

広告を自動広告⁠‎フォーマットと自動最適化⁠‎テストにしているためheadタグ内でAdSense コードを出力するのみにしています。
手動で広告の配置を行い場合は、設置したい箇所のテンプレートでコードの追加をしてください。

本番環境とステージング、ローカルとでタグそのものを出力しないようできます。
環境変数は .evn などで指定してください。

ADSENSE_CLIENT_ID=ca-pub-00000000000000
import { getTagList } from '@/libs/microcms';
import { LIMIT } from '@/constants';
import Header from '@/components/Header';
import Footer from '@/components/Footer';
import Nav from '@/components/Nav';
import './globals.css';
import styles from './layout.module.css';
// 1. ライブラリを呼び出す
import { GoogleTagManager } from '@next/third-parties/google'

export const metadata = {
  metadataBase: new URL(process.env.BASE_URL || 'http://localhost:3000'),
  title: {
    template: '%s | Simple Blog',
    default: 'Simple Blog',
  },
  description: 'A simple blog presented by microCMS',
  openGraph: {
    title: {
      template: '%s | Simple Blog',
      default: 'Simple Blog',
    },
    description: 'A simple blog presented by microCMS',
    images: '/ogp.png',
  },
  alternates: {
    canonical: '/',
  },
};

type Props = {
  children: React.ReactNode;
};

export default async function RootLayout({ children }: Props) {
  const tags = await getTagList({
    limit: LIMIT,
  });

  return (
    <html lang="ja">

      {/* 2.環境変数でクライアントIDを指定、なければ出力されない */}
      {process.env.ADSENSE_CLIENT_ID && (
        <script
          async
          src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${process.env.ADSENSE_CLIENT_ID}`}
          crossOrigin="anonymous"
        />
      )}

      <body>
        <Header />
        <Nav tags={tags.contents} />
        <main className={styles.main}>{children}</main>
        <Footer />
      </body>
    </html>
  );
}

現場からは以上です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?