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
- Visit Google Analytics and log in with your Google account.
- Click βStart Measuring β in the initial popup.

- Fill in your business data. One account can be used for multiple websites:
- Create Account β Properties β Business Info β Destination β Start Data Collection

- 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
- Once the property has been created, you will enter the Analytics dashboard.

- Enter your website domain and name the stream (feel free, just be clear).

- 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!
π‘ Bonus Tips With Google Analytics, you can:
- Analyze the performance of each page
- Track real-time traffic
- Integrate with Google Ads & Tag Manager