This article describes how to set up a web page for Google Analytics 4 (GA4) properties with gtag.js. Learn more about GA4 properties.
The global site tag (gtag.js) is a JavaScript tagging framework and API that allows you to send event data to Google's measurement products. The default tag provided by Google Analytics is based on gtag.js, and can be obtained directly from within Google Analytics. You can also deploy Google Analytics from Tag Manager. If you'd like to compose your own Analytics tag, or integrate an additional Analytics property with an existing gtag.js installation, then this article is for you.
Install a new tag
To install Google Analytics when no existing global site tag exists, use this
prototype. Replace MEASUREMENT_ID
with the ID of the Google Analytics property
to which you want to send data. This code should appear immediately after the
opening <head>
tag. You need only one global snippet per page.
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=MEASUREMENT_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'MEASUREMENT_ID');
</script>
This code loads the gtag.js library, establishes a default Google Analytics
measurement ID, and automatically sends a page_view
event to Google Analytics.
Add an additional Google Analytics property to an existing tag
To configure a second Google Analytics property, add an additional config
command. To build on the previous example, add a new config entry and replace
MEASUREMENT_ID_2
with the ID from a second Google Analytics account:
<script async src="https://www.googletagmanager.com/gtag/js?id=MEASUREMENT_ID">
</script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'MEASUREMENT_ID');
gtag('config', 'MEASUREMENT_ID_2');
</script>
It is also possible to add Google Analytics to global site tags that originated from other products such as Google Ads, Floodlight, etc. Learn more.
Related resources
- Google Analytics help center: Get started with Analytics
- Google Analytics help center: Implementation guide for gtag.js
- Google Developers: gtag.js Developer Guide
- Google Tag Manager help center: Google Analytics 4 tags