How do I install GA4 using gtag.js?

Applies to: Google Analytics 4 (GA4)
Last updated: May 2025


Problem

You want to install Google Analytics 4 on your website using the gtag.js (Global Site Tag) method, but you’re not sure where or how to place the code.


Solution

To install GA4 using gtag.js, you’ll add a short JavaScript snippet to the <head> section of every page on your site. This snippet loads the tracking library and sends pageview data to your GA4 property.


Step-by-Step Guide

1. Get Your Measurement ID

  1. Go to https://analytics.google.com
  2. Select your GA4 property
  3. Click Admin (⚙️) > Under Property, choose Data Streams
  4. Click your Web stream
  5. Copy the Measurement ID (e.g., G-XXXXXXX)

2. Add the Global Site Tag (gtag.js) to Your Website

Paste the following code inside the <head> section of every HTML page:

<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());

gtag('config', 'G-XXXXXXXXXX');
</script>

Replace 'G-XXXXXXXXXX' with your actual Measurement ID


3. Save and Publish

  • Save changes to your HTML or template files
  • If using a CMS (like WordPress, Joomla, etc.), place the code via:
    • Header settings in your theme
    • A plugin (like “Insert Headers and Footers”)

4. Test Your Installation

  • Go to Google Analytics > Realtime
  • Open your website in a new browser tab
  • You should appear in the real-time overview within 30 seconds

Optional: Use the Google Tag Assistant Chrome extension to verify tags are firing correctly.


Best Practices

  • Place the tag high in the <head> to ensure early firing
  • Use only one instance of gtag.js per page
  • Avoid mixing UA and GA4 tracking IDs in a single tag unless you intend to dual-track

Troubleshooting

IssueSolution
Real-time data not showingDouble-check Measurement ID and page placement
Multiple tags on pageRemove any duplicate or outdated tags
DataLayer not definedMake sure gtag() and dataLayer are initialized properly

You may also like...