iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐡

Trying out DebugView in GA4 (Web) now that it's available

に公開

Last year, when GA4 was first released, I didn't think DebugView was available, but it seems it is now, so I decided to give it a try.

In a professional setting, GA properties and tracking IDs are usually split between staging and production environments. However, for personal use, it's much easier to manage everything with a single ID. This definitely makes things simpler...!

What is DebugView

[GA4] Monitor events in debug mode

You can monitor events and other data in real-time like this.
I've used it with Firebase for Android and iOS apps and found it very convenient, so I was looking forward to using it on the Web as well.

Implementation in Next.js

This setup uses Next.js and TypeScript.

First, let's add the type definitions.
While you could manually add them to window.d.ts, I'll just install the package to save some trouble.

npm i -D @types/gtag.js
# or
yarn add -D @types/gtag.js

When using Next.js, you would typically implement it as follows.
We'll keep this part unchanged and proceed with the usual implementation.

lib/gtag.ts
export const GA_TRACKING_ID = process.env.NEXT_PUBLIC_GA_ID || '';

export const pageview = (url: string): void => {
    if (!GA_TRACKING_ID) return;

    window.gtag('config', GA_TRACKING_ID, {
        page_path: url,
    });
}

export const event = (...) => { /* Omitted */ }

Loading gtag.js in _document.tsx

I don't like to clutter the Head tag, so I'll extract it into a separate component.

I'm copying and pasting the gtag.js call into the dangerouslySetInnerHTML of the second script tag. Then, by passing debug_mode: true to the options in the third argument of gtag('config') when in a non-production environment, DebugView becomes enabled. That's all the work involved.

Gtag.tsx
import { VFC } from 'react';
import { GA_TRACKING_ID } from '@/lib/gtag';

const isProduction = process.env.NODE_ENV === 'production';

export const GlobalSiteTag: VFC = () => {
    if (!GA_TRACKING_ID) return null;

    return (
        <>
            <script async src={`https://www.googletagmanager.com/gtag/js?id=${trackingId}`}></script>
            <script
                dangerouslySetInnerHTML={{
                __html: `
                    window.dataLayer = window.dataLayer || [];
                    function gtag(){dataLayer.push(arguments);}
                    gtag('js', new Date());
                    gtag('config', ${isProduction ? `'${GA_TRACKING_ID}'` : `'${GA_TRACKING_ID}', { debug_mode: true }`});
                `,
                }}
            />
        </>
    )
}

_document.tsx
import Document, { Html, Head, Main, NextScript } from 'next/document';
import { GlobalSiteTag } from '@/components/script/Gtag';

export default class MyDocument extends Document {
  render(): JSX.Element {
    return (
      <Html lang='ja'>
        <Head>
            <GlobalSiteTag />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

Discussion