NextJS

Next js에 구글 애널리틱스 (Google Analytics) 달기

FE 2022. 6. 23. 14:23

https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications

 

Single Page Application Measurement  |  Analytics for Web (analytics.js)  |  Google Developers

Single Page Application Measurement This guide describes how to use analytics.js to measure page activity on sites whose content is loaded dynamically without traditional full page loads. Overview A Single Page Application (SPA) is a web application or web

developers.google.com

Google Analytics 연동을 위해 Next.js에 작업을 해주었습니다.

 

일단 Google Analytics 연동은 그렇게 어렵지 않습니다.

// _document.tsx
import Document, { Html, Head, Main, NextScript } from "next/document";

const isProduction = process.env.APP_ENV === "production";

export default class RootDocument extends Document {
  render() {
    return (
      <Html lang="ko">
        <Head>
          {isProduction && (
            <>
              <script
                async
                src={`https://www.googletagmanager.com/gtag/js?id=[${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}]`}
              />
              <script
                dangerouslySetInnerHTML={{
                  __html: `
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());
                gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}', {
                  page_path: window.location.pathname,
                });
                ga('send', 'pageview', location.pathname);
              `,
                }}
              />
            </>
          )}

          <link rel="shortcut icon" href="/favicon/favicon.svg" />
          <meta charSet="UTF-8" />
        </Head>
        <body id="body">
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }

Production 환경에서만 GA 추적이 되어야 하기 때문에 그 분기처리와 함께 Google Analytics 키 값을 설정해주면 됩니다. 그러나 여기서 하나 문제가 있습니다.

 

위의 Docs를 보면 더 자세히 설명되어 있지만 간단하게 짚고 넘어가면 GA 태그는 사용자가 새 페이지를 로드할 때마다 스니펫 코드가 실행되기 때문에 기존 웹 사이트에서는 잘 동작합니다. 그러나 SPA 패러다임에서는 동적으로 새 페이지 콘텐츠를 로드하기 때문 analytics.js 스니펫 코드는 한번만 실행됩니다. 이러면 새 콘텐츠가 로드될 때 후속 페이지뷰를 수동으로 추적할 수 있게 해줘야 합니다.

 

즉, SPA 패러다임에서는 첫 페이지만 감지하고 실시간 감지가 되지 않습니다. 새로고침을 눌러줘야 감지가 되기 때문에 Tracking Virtual Pageviews 설정을 해줘야 합니다.

 

Docs를 보고 function 설정을 해주었지만 제가 어떤 부분을 놓쳤는지 실시간 감지가 계속해서 되지 않더라고요. 그래서 결국 라이브러리를 선택했습니다. ga 관련 가장 유명한 라이브러리인 react-ga를 설치하여 해결할 수 있었습니다.

// useGaTracking
import ReactGA from "react-ga";

const useGaTracking = () => {
  // useEffect
  const router = useRouter();

  useEffect(() => {
    ReactGA.initialize("yourKey(trackingId)");
    ReactGA.set({ page: window.location.pathname });
    ReactGA.pageview(window.location.pathname);
  }, [router]);
  return <></>;
};

 

이렇게 customHook으로 빼주어서 router가 바뀔때마다 감지하게끔 의존성을 걸어줘서 해결했습니다.

원래는 페이지가 단일값으로만 있던 페이지뷰 수들이 각 페이지에 방문할 때마다 실시간으로 감지되어 좀 더 명확하게 GA를 활용할 수 있게 되었습니다.