DEV Community

Suraj Sharma
Suraj Sharma

Posted on • Originally published at surajsharma.net

How to add google analytics to a Next.js website

In this tutorial, you'are going to learn how you can add Google Analytics to your Next.js Website.

A typical Google Analytics JavaScript code looks like this

<script async src="https://www.googletagmanager.com/gtag/js?id=${YOUR_TRACKING_ID}"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', ${YOUR_TRACKING_ID});
</script>
Enter fullscreen mode Exit fullscreen mode

Adding this directly inside the Head component on your Next project does not work because React converts it to a string before rendering,
which helps prevent cross-site-scripting attack

The best way to add the google analytics script

Open your _document.js file, use the below code to insert the script into your _document.js file.

import Document, { Head, Main, NextScript } from 'next/document';

export default class MyDocument extends Document {
  render() {
    return (
      <html lang="en">
        <Head>
          <script async src="https://www.googletagmanager.com/gtag/js?id=${YOUR_TRACKING_ID}"></script>
          <script
            async
            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>
    )
  }
}
Enter fullscreen mode Exit fullscreen mode

Replace the ${YOUR_TRACKING_ID} variable with your google analytics tracking ID

Now when you reload your website you can notice one 'Active Users right now' on your google analytics dashboard.

add google analytics to nextjs website

Top comments (0)