프론트엔드/Next.js

[Next.js] Next15 앱라우터 환경에서 구글 애널리틱스(GA | gtag.js) 적용 방법

순코딩 2025. 3. 13. 15:07

설치

npm install @next/third-parties@latest

 

예시 코드

구글 애널리틱스에서 제공된 GA(gtag.js) 값 복사

<!-- 구글이 제공한 Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id='G-1234..."> // ✨ gaid 복사('G-1234..)
</script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-1234...');  // ✨ gaid 복사('G-1234...')
</script>

 

app > src > layout.tsx 에 아래와 같이 붙여넣기
import { GoogleAnalytics } from '@next/third-parties/google' // ✨


export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="ko">
      <body>
            {children}
      </body>
      <GoogleAnalytics gaId="'G-1234..." /> // ✨
    </html>
  );
}

 

배포 후 구글 애널리틱스를 확인하면 정상적으로 GA가 등록된 것을 확인할 수 있습니다.

 

참고자료

https://nextjs.org/docs/messages/next-script-for-ga#use-nextthird-parties-to-add-google-analytics

 

Using Google Analytics with Next.js (through `next/script`)

Prefer next/script component when using the inline script for Google Analytics. An inline script was used for Google Analytics which might impact your webpage's performance. Instead, we recommend using next/script through the @next/third-parties library. @

nextjs.org

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

 

Optimizing: Third Party Libraries | Next.js

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

nextjs.org