add google analytics to next.js code example

Example 1: google analytics analytics next.js

do the following in _document.js or wherever you defined Head:

<Head>
  <script
    async
    src="https://www.googletagmanager.com/gtag/js?id=[Tracking ID]"
  />

  <script
    dangerouslySetInnerHTML={{
      __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '[Tracking ID]');
        `,
    }}
  />
</Head>

Example 2: google analytics nextjs

npm i -D @types/gtag.js