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">
          {/* Global Site Tag (gtag.js) - Google Analytics */}
              __html: `
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());

                gtag('config', 'YOUR_TRACKING_ID');
          <Main />
          <NextScript />

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.