How to Set Up Google Analytics on a Site Built with Vercel
Introduction
After publishing a site on Vercel, you need an analytics tool such as Google Analytics to understand traffic.
In this article, I will walk through how to set up Google Analytics in a Vercel environment by getting a measurement ID in Google Analytics, storing it as a Vercel environment variable, and loading it through an Astro component.
What you will learn
- What Google Analytics is and why it matters
- How to connect Vercel and Google Analytics
- The meaning of the terms that often appear during setup
- How to verify that everything is working and how to handle common issues
Common setup sticking points
After publishing a site on Vercel, many people run into the same problems:
- What is an “environment variable,” and where do I set it?
- I was told to add something to the code, but I do not know where to put it
- I set everything up, but nothing appears in the Google Analytics dashboard
These are common sticking points for people who are not engineers. When documentation assumes the basics, the overall setup flow can be difficult to follow.
First, understand the overall flow
The setup has three phases:
- Prepare Google Analytics and get a measurement ID
- Configure Vercel and store the measurement ID as an environment variable
- Update your code so your site sends data to Google Analytics
All three parts are required. If one is missing, the setup will not work, so it is important to follow the steps in order.
In this guide, I will explain how to do this on a site built with Astro.
Step-by-step guide
What is Google Analytics?
Google Analytics is a website analytics tool provided by Google.[1]
It automatically collects information such as:
- Number of visitors: how many people visited your site
- Page views: how many times each page was viewed
- Time on site: how long users stayed
- Traffic sources: where visitors came from, such as Google search, social media, or direct visits
- User flow: how people moved from one page to another
With this data, you can see which pages are popular, where readers leave the site, and what you can improve.
Step 1: Prepare your Google Analytics account
Go to the official Google Analytics site at https://analytics.google.com. Sign in with your Google account and follow the on-screen instructions to create an account and property.
When the setup is complete, you will receive a measurement ID in the form G-XXXXXXXXXX.
Important: You will need this measurement ID in the next step. Make sure you keep it handy.
Step 2: Set an environment variable in Vercel
What is an environment variable?
An environment variable is a secure way to store a value that should only be used in a specific environment, such as your production site.
Think of it like a locked drawer. Instead of writing the measurement ID directly into your code, you place it in this drawer and let the code read it from there. That keeps the value out of any public code repository.
How to set it up
- Log in to the Vercel dashboard
- Select the project you want to configure
- Click the Settings tab at the top
- Open Environment Variables from the left-hand menu
- Add a new variable with the following values:
| Item | Value |
|---|---|
| Key | PUBLIC_GA_ID |
| Value | G-XXXXXXXXXX (your measurement ID) |
- Click Save[2]
Why does the variable name start with
PUBLIC_? Astro exposes only environment variables prefixed withPUBLIC_to client-side code. Variables withoutPUBLIC_are intentionally hidden from browser-side code for security reasons.[3]
Step 3: Add the integration code
Next, add the code that connects your site to Google Analytics. The variable name is PUBLIC_GA_ID, but if you were using Next.js, it would be NEXT_PUBLIC_GA_ID. The exact name depends on the framework you use.
If you are using Astro, create the following file in src/components/:
GoogleAnalytics.astro
---
const gaId = import.meta.env.PUBLIC_GA_ID;
---
{gaId && (
<>
{/* Speed up script loading */}
<link rel="preconnect" href="https://www.googletagmanager.com" crossorigin />
<link rel="dns-prefetch" href="https://www.googletagmanager.com" />
<link rel="preconnect" href="https://www.google-analytics.com" crossorigin />
{/* Google Tag Manager script */}
<script async src={`https://www.googletagmanager.com/gtag/js?id=${gaId}`}></script>
{/* Page view tracking script */}
<script is:inline define:vars={{ gaId }}>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', gaId, { send_page_view: false });
function sendPageView() {
gtag('event', 'page_view', {
page_location: window.location.href,
page_title: document.title,
transport_type: 'beacon',
});
}
if (!window.__gaListening) {
window.__gaListening = true;
document.addEventListener('astro:page-load', sendPageView);
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', sendPageView, { once: true });
} else {
sendPageView();
}
</script>
</>
)}What the code does This script reads the measurement ID from an environment variable and sends page view data to Google Analytics.
Step 4: Add the component to your layout
Now include GoogleAnalytics.astro inside the <head> section of your site so it loads on every page. In many Astro projects, this means adding it to a layout file such as src/layouts/BaseLayout.astro.
---
import GoogleAnalytics from '../components/GoogleAnalytics.astro';
---
<html>
<head>
<GoogleAnalytics />
<!-- Other head content -->
</head>
<body>
<!-- Page content -->
</body>
</html>Important things to check
After finishing the setup, confirm the following.
How to verify that it works
- Deploy your changes to Vercel
- Open the published site in your browser
- Go to Google Analytics and open Reports > Realtime
- If you appear as an active user, the setup is working
It may take a few minutes for data to appear. If you do not see anything right away, wait 5 to 10 minutes and check again.
Common issues and fixes
| Symptom | Possible cause | Fix |
|---|---|---|
| No data is recorded at all | The environment variable name is wrong | Check the spelling of PUBLIC_GA_ID |
| You do not appear in Realtime | An ad blocker is active | Temporarily disable browser extensions and try again |
| The measurement ID is not being read | The deployment has not finished | Check the Vercel deployment logs |
Try it now
Once Google Analytics is set up, data will start collecting automatically. Splitting the work into three steps makes the points to check clear.
Summary
In this article, I covered how to set up Google Analytics on a Vercel site:
- Google Analytics is Google’s tool for measuring website traffic
- Get your measurement ID (
G-XXXXXXXXXX) and store it as a Vercel environment variable - Add the integration component to your site so every page sends data
- Verify the setup using the Realtime report after deployment
Terms like environment variable and component become easier to manage once their roles are separated.
See the references for the external specifications and background sources used on this page.[2]
References
- Google, Google Analytics
- Vercel, Environment Variables, Vercel Docs
- Astro, Environment variables, Astro Docs