How to Set Up and Verify Google Analytics on Vercel
What you’ll learn
- How to configure the Google Analytics measurement ID, Vercel environment variable, and Astro code as separate layers
- How to load the Google tag as a component and avoid duplicate manual and automatic pageviews
- Completion checks covering privacy, consent, Realtime, DebugView, and Tag Assistant
Separate Vercel Environment Variables from Analytics Loading
Reliable analytics on an Astro site hosted by Vercel requires separate checks for the measurement ID, environment variable, code-loading location, and browser event delivery. Completing only one of those steps can leave the site looking configured while no data is collected. The completion criteria also include privacy and consent review.
By the end of this article, you will have practical criteria for answering “In what order should I configure and verify the measurement ID, environment variable, loading code, and consent?” in your own context.
Work Through Vercel Configuration, Implementation, and Verification
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. I use a Vercel environment variable so the measurement ID can be managed per environment. Using an environment variable is not itself a Google Analytics requirement.
This is an implementation example that combines a GA4 measurement ID, Google tag (gtag.js), Vercel environment variables, and an Astro component. Google Analytics, Vercel Analytics, and Google Tag Manager are separate systems, so I keep those assumptions separate.
A Verified Setup Loads on Production Pages and Receives Events
- 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
Mixing the Measurement ID, Environment Variable, and Load Location Blocks Setup
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.
Work Through the Measurement ID, Environment, and Code Layers
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
The setup shown in this article uses all three parts. It is technically possible to put a measurement ID directly in source code, but this guide uses an environment variable to separate environment-specific configuration from code.
In this guide, I will explain how to do this on a site built with Astro.
Add the Google Tag to Your Site
What is Google Analytics?
Google Analytics is a Google service that collects site or app activity as events and makes it available in reports.[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.
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.
After creating a web data stream, you can find a measurement ID, which usually begins with G-.[6]
Important: You will need this measurement ID in the next step. Make sure you keep it handy.
Set an Environment Variable in Vercel
What is an environment variable?
An environment variable is a way to store a value that should vary by environment, such as your production site.[2]
The GA4 measurement ID is not a secret key. A value exposed through a public client-side variable will be visible in the browser, so it must not contain secrets. The reason to use an environment variable here is environment separation and cleaner configuration management, not secrecy.
Register the Variable Name, Value, and Target Environments in Vercel
- 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]
Add the Integration Code
Next, add the code that connects your site to Google Analytics with the Google tag (gtag.js). The G-XXXXXXXXXX value is a GA4 measurement ID. It is different from a Google Tag Manager container ID such as GTM-XXXXXXX. 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.[3]
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 (gtag.js) 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() {
const pageLocation = window.location.href;
if (window.__gaLastPageLocation === pageLocation) return;
window.__gaLastPageLocation = pageLocation;
gtag('event', 'page_view', {
page_location: pageLocation,
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.
Do Not Combine Manual and Automatic Pageviews
This example sets send_page_view: false to disable the automatic pageview on initialization, then sends page_view manually on astro:page-load. The __gaLastPageLocation check prevents two initial events for the same URL. If “Page changes based on browser history events” is enabled in Google Analytics enhanced measurement, client-side navigation may also be measured through that automatic path. Choose either the automatic or manual strategy and avoid sending the same navigation through both.[7]
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>Check Privacy and Behavior Before Collecting Data
After finishing the setup, confirm the following.
Privacy and consent management
When Google Analytics is added, information about a visitor’s device, browser, and access activity is sent to Google. On a public site, disclose the use of Google Analytics in the privacy policy and the site owner must confirm whether the target regions and measurement method call for cookie consent or Consent Mode.[4][5]
This does not mean every site must show the same cookie banner. The right implementation depends on region, data collected, purpose of use, and the organization’s privacy policy. Also confirm Google Analytics terms, data processing conditions, and internal legal or privacy requirements where applicable.[4]
Verify with Realtime, DebugView, and Tag Assistant
- Deploy your changes to Vercel
- Open the published site in your browser
- Use Tag Assistant to confirm that the Google tag is detected and sending events
- Use DebugView to confirm one
page_viewfor the initial load and one for each client-side navigation - Open Reports > Realtime in Google Analytics and confirm the visit[8]
Realtime can have a reporting delay. If nothing appears, do more than wait: check Tag Assistant, DebugView, browser network requests, the measurement ID, and consent state in sequence.[8]
If Events Are Missing, Check the ID, Consent, and Loading State
| 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 |
One navigation produces multiple page_view events | Automatic and manual tracking overlap | Inspect the source in DebugView and keep one strategy |
Use a Checklist to Decide When Setup Is Complete
Record the setup as complete when all of these checks pass:
-
PUBLIC_GA_IDexists in the target Vercel environment and the redeployment is complete - The published HTML loads the Google tag
- The initial load and each client-side navigation send one
page_view - Realtime or DebugView shows the expected event
- The privacy policy, consent requirements, and internal policy have been reviewed
Summary: Separate the Measurement ID, Loading, and Consent Checks to Verify Analytics
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, in this guide, store it as a Vercel environment variable - Add the integration component to your site so every page sends data
- After deployment, use Realtime, DebugView, and Tag Assistant to confirm that initial loads and client-side navigations do not send duplicate
page_viewevents
Terms like environment variable and component become easier to manage once their roles are separated.
Start by confirming that the measurement ID matches the environment variable for the target environment, then verify event delivery on the published page. If your site architecture, consent requirements, or Google Analytics configuration differs, adapt the example to the current product settings and your organization’s policy.
This article is a general information summary and is not legal advice. Confirm practical decisions with a qualified specialist.
References
- Google, Data collection, Google Analytics Help
- Vercel, Environment Variables, Vercel Docs
- Astro, Environment variables, Astro Docs
- Google, Safeguarding your data, Google Analytics Help
- Google, Set up consent mode on websites, Google Analytics Help
- Google, Find your Google tag ID, Google Analytics Help
- Google, Measure pageviews, Google for Developers, updated June 9, 2026
- Google, Verify and troubleshoot your Google Analytics setup, Google for Developers, updated June 8, 2026
For the latest releases and updates, check the official website and official documentation.