Background paper texture
nextjschrome

Integrate Google Analytics on Website with Next.js

πŸ’‘ How to Quickly Integrate Google Analytics on Next.js Website (It Only Takes 5 Minutes!).

Author avatar

Peter Shaan

May 20, 2025


116 Views

Today I will share step-by-step how to connect Google Analytics to your website that uses Next.js. This will also be my own notes so I don't forget next time πŸ˜…

What is Google Analytics?

Simply put, Google Analytics is a free tool from Google that helps us to:

  • See the number of visitors to our website
  • Know their country of origin
  • Tracking the most visited pages
  • And many other insights!

In essence, you can monitor website performance directly from the Google dashboard, without any hassle.


Step 1 - Sign up & Create a Google Analytics Account

  1. Visit Google Analytics and log in with your Google account.
  2. Click β€œStart Measuring ” in the initial popup.
  1. Fill in your business data. One account can be used for multiple websites:
    • Create Account β†’ Properties β†’ Business Info β†’ Destination β†’ Start Data Collection
  1. Choose the platform. Since we are using a website, click the Web option.
    If you don't have a public domain, you can skip this step first.

Step 2 - Create Data Stream & Obtain Tag IDs

  1. Once the property has been created, you will enter the Analytics dashboard.
  1. Enter your website domain and name the stream (feel free, just be clear).
  1. You will get a Measurement ID (example: G-XXXXXXX). Note and save this ID, as we will use it in the next step.

Step 3 - Install Google Analytics to Website

Google gives you two options:

  • Install manually (directly in HTML)
  • Use a CMS or other integration

πŸ“› But the manual method is less secure, because the ID can be seen in the source code.


Step 4 - Google Analytics Integration in Next.js

Now this is the most important part We will install Google Analytics into your Next.js project using a modern & clean way.

1. Install Package

npm install third-parties

2. Create .env File

Create file .env.local in root of nextjs project, and add this line;

NEXT_PUBLIC_GA_TRACKING_ID=G-XXXXXXX

3. Add to Layout App

import { GoogleAnalytics } from "@next/third-parties/google";
<GoogleAnalytics gaId={process.env.GA_TRACKING_ID || ''} />

or it could be better if you add an ENV Production Node to make it the same as mine.

Push & update ENV Server

If you use hosting like Vercel, don't forget to update the environment variables on the Vercel dashboard too.

πŸŽ‰ Done! Google Analytics is now live!

Your website is now officially connected to Google Analytics!

Google Analytics

πŸ’‘ Bonus Tips With Google Analytics, you can:

  • Analyze the performance of each page
  • Track real-time traffic
  • Integrate with Google Ads & Tag Manager