Blog>
Snippets

Adding Google Analytics to Next.js 14

Show how to integrate Google Analytics in a Next.js 14 application by injecting the tracking script into the custom _document.js.
import Document, { Html, Head, Main, NextScript } from 'next/document';

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx);
    return { ...initialProps };
  }

  render() {
    return (
      <Html lang="en">
        <Head>
          {/* Global Site Tag (gtag.js) - Google Analytics */}
          <script
            async
            src={`https://www.googletagmanager.com/gtag/js?id=YOUR_TRACKING_ID`}
          />
          <script
            dangerouslySetInnerHTML={{
              __html: `
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());

                gtag('config', 'YOUR_TRACKING_ID');
              `,
            }}
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;
This code snippet shows how to customize the _document.js file in a Next.js 14 application to include Google Analytics. Replace 'YOUR_TRACKING_ID' with your actual Google Analytics tracking ID. The <script> tags are added to the <Head> to asynchronously load the Google Analytics gtag.js script and to define the gtag function for sending data to Google Analytics.