Next.js

[Next] Google Analytics 적용하기 두 줄 요약

Chunho 2022. 10. 17. 18:50

NextJS 환경에서 Google Analytics는 다음과 같이 적용할 수 있다.

1. lib폴더에 gtag.js 파일을 생성한다.

 

export const GA_TRACKING_ID = `${process.env.NEXT_PUBLIC_GA_TRACKING_ID}`

// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
export const pageview = (url) => {
    window.gtag('config', GA_TRACKING_ID, {
        page_path: url
    })
}

// https://developers.google.com/analytics/devguides/collection/gtagjs/events
export const event = ({ action, category, label, value }) => {
    window.gtag('event', action, {
        event_category: category,
        event_label: label,
        value: value
    })
}

2. _app.tsx 파일에 아래 코드를 넣어준다.

 

function App({Component, pageProps}: AppProps) {
  // GA 설정 시작
  const router = useRouter()
  useEffect(() => {
    const handleRouteChange = (url: any) => {
      gtag.pageview(url)
    }
    router.events.on('routeChangeComplete', handleRouteChange)
    router.events.on('hashChangeComplete', handleRouteChange)
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange)
      router.events.off('hashChangeComplete', handleRouteChange)
    }
  }, [router.events])
  // GA 설정 끝

  return (
    <>
     
      {/* GA 설정 시작 */}
      {/* Global Site Tag (gtag.js) - Google Analytics */}
      <Script
        strategy="afterInteractive"
        src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_TRACKING_ID}`}
      />
      <Script
        id="gtag-init"
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{
          __html: `
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', '${process.env.NEXT_PUBLIC_GA_TRACKING_ID}', {
          page_path: window.location.pathname,
        });
      `
        }}
      />
      {/* GA 설정 끝 */}
   
                <Component {...pageProps} />

    </>
  )
}

위와 같이 간단하게 적용해 줄 수 있다.