본문 바로가기
React.js / Next.js

[nextjs] router 에서 구글 애널리틱스(Google Analitics) google tag manager 적용

by ahnshy 2024. 10. 13.

https://tagmanager.google.com/

구글 태그매니저로 구글 애널리틱스 적용하려면, 자바스크립트 코드를 추가해야하는데, 고대로 복붙하면 적용되지 않는다. 

다음을 참고하면 된다. 

https://nextjs.org/docs/app/building-your-application/optimizing/third-party-libraries

 

Optimizing: Third Party Libraries | Next.js

Optimize the performance of third-party libraries in your application with the `@next/third-parties` package.

nextjs.org

 

설치

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

 

다음 코드를 layout.tsx에 적용

import { GoogleTagManager } from '@next/third-parties/google'
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <GoogleTagManager gtmId="GTM-XYZ" />
      <body>{children}</body>
    </html>
  )
}

 

 

구글 애널리틱스는 다음과 같은 방법으로 : 

import { GoogleAnalytics } from '@next/third-parties/google'
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>{children}</body>
      <GoogleAnalytics gaId="G-XYZ" />
    </html>
  )
}