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を利用したサイトにGoogleタグマネージャーのタグを入れる方法です。

やりたいこと

Googleタグマネージャーのタグをサイトに入れたい。
ただし、Googleアナリティクスの計測タグはGoogleタグマネージャーに含める。

事前準備

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

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

同ページにGoogleタグマネージャーを利用する場合のコード例も出ていますので参照してください。

フロント側での利用

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

オリジナル

追加した部分

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

GOOGLE_GTM_ID=GTM-XXXXXXXX
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.GOOGLE_GTM_ID && (
        <GoogleTagManager gtmId={process.env.GOOGLE_GTM_ID} />
      )}

      <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?