Setup Google Analytics for Next.js website

August 22, 2022

Intro

Google Analytics is a great tool to collect and analyze data from websites and mobile apps to help companies and teams grow. It's free and easy to use and has many excellent features like real-time overviews and reports. Today we will learn how to integrate it with Next.js one of the best web frameworks recently to get the best benefit of both.

Setup a Google Analytics account

First of all, you should have a Gmail Account, if you don't have on create one before jumping to the next step.

Go to Google Analytics Dashboard.

If this is the first time to log into Google Analytics Dashboard, you will see this screen, click on “start measuring” and create account and property

Google Analytics Home page

If you already have an account, go to “Admin” on the sidebar.

Google Analytics Dashboard

After creating the account and property, you should see this screen.

New property

All that we need from this screen is the measurement id.

Setup Google Analytics for Next.js

In your project folder, find the file pages/_app.js and we need to import the <Script /> component.

import Script from "next/script";

and then add the following code to the JSX:

<Script
  src="https://www.googletagmanager.com/gtag/js?id=YOUR_MEASUREMENT_ID"
  strategy="afterInteractive"
/>

<Script id="google-analytics" strategy="afterInteractive">
  {
    `
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'YOUR_MEASUREMENT_ID');
    `;
  }
</Script>

That's it, congratulations! You can now start measuring your website with Google Analytics 🎉