Sub topic 5
Install the Google tag directly in your site's HTML
This chapter covers the manual route: pasting the Google tag into your site's HTML yourself. It assumes you already have a GA4 property with a web data stream and know where to find its Measurement ID (format G-XXXXXXXXXX). It also assumes you can edit a page template, understand what a <script> tag in the <head> does, and know the basic idea of events and sessions.
When the manual route fits
A manual install gives you full control over where the tag loads and what it does before it sends data. It suits these cases:
- A hand-built or static site, or a custom application, where you control the templates.
- A site on a platform that has no GA4 integration, but lets you edit the head.
- Pages where you must set consent defaults or configuration options before the first hit is sent.
It is a poor fit when many people edit tracking on the site. In that case Google Tag Manager, covered in a later chapter, gives you versioning and a publishing workflow. It is also a poor fit when a platform plugin already does the job correctly.
Get the snippet
In GA4, open Admin, then Data streams, and select your web stream. Choose View tag instructions, then Install manually. Google shows a snippet with your Measurement ID already filled in. Copy that one, since it is always current. The standard form looks like this, with G-XXXXXXXXXX standing in for your own ID:
<!-- 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>What each line does
The snippet has two <script> blocks, and each has a separate job.
- The first block loads the library
gtag.jsfrom Google's servers. Theasyncattribute lets the browser keep parsing the page while the file downloads, so the tag does not block rendering. Theidin the URL tells the library which stream to configure. window.dataLayer = window.dataLayer || [];creates a global array nameddataLayerif one does not exist yet. Using||means the line is safe if another script has already created it.function gtag(){dataLayer.push(arguments);}defines a small helper. Every call togtag(...)pushes its arguments ontodataLayer. The library reads that queue and processes it in order. Because of this, the inline code can run beforegtag.jshas finished downloading, and no commands are lost.gtag('js', new Date());records the time the tag started.gtag('config', 'G-XXXXXXXXXX');initializes the stream. It sets up measurement for that ID and sends the firstpage_viewevent.
The helper pushes arguments, not an array of the parameters. That detail matters if you ever rewrite the helper using rest parameters or an arrow function. The library expects the arguments object, so the rewritten version can silently fail to be processed.
Where to put it
Place the snippet in the <head> of every page you want measured, as high as practical. Putting it early means the tag loads before most other scripts, so fast visitors who leave quickly are still counted.
- On a site with a shared layout or template, add it once to that template. This is the best option, because every page then inherits it.
- On a static site with separate files, add it to each file. Missing one page means that page produces no data.
- In a single-page application, add it once to the main HTML file (often
index.html), not inside a component.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- 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>
<title>Home</title>
</head>
<body>
<h1>Hello</h1>
</body>
</html>Configuration options on the config call
The config command accepts a third argument, an object of parameters that apply to every event sent from that page. A common one while testing is debug_mode, which flags events so they appear in the DebugView report:
gtag('config', 'G-XXXXXXXXXX', {
debug_mode: true
});Remove it, or make it conditional, before you leave it on in production. Debug events still count as normal data in standard reports. The flag only makes them visible in DebugView.
Two other options matter often enough to know about:
| Option | Effect | When to use it |
|---|---|---|
| `send_page_view: false` | Stops the automatic `page_view` on config | Single-page apps where you send page views yourself on route changes |
| `debug_mode: true` | Marks events for DebugView | Testing only |
Consent defaults come before config
If privacy rules in your region or your organization require consent before analytics storage is used, set the default state before the config call. The tag then reads the default on the first page load. If config runs first, the tag may already have sent data.
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('consent', 'default', {
ad_storage: 'denied',
ad_user_data: 'denied',
ad_personalization: 'denied',
analytics_storage: 'denied'
});
// The gtag('config', 'G-XXXXXXXXXX') call comes after this default.In the page, the order of statements inside the inline script is therefore: define dataLayer and gtag, set the consent default, then call js and config. A consent banner later calls gtag('consent', 'update', {...}) with the visitor's choices. A later chapter covers consent in more detail.
Order of operations on a page
The sequence below shows what happens when a visitor loads a page that carries the snippet.
Step-by-step: install and check
- Copy the snippet from Install manually in your web data stream.
- Paste it into the
<head>of your shared template, directly after the<meta charset>tag. - If you need consent defaults, put the
consentdefault call after thegtagfunction definition and beforeconfig. - Deploy the change. A cached or unpublished template is a common reason the tag seems absent.
- Open the site in a browser and view the page source. Search for your Measurement ID and confirm it appears exactly once.
- In GA4, open Reports, then Realtime, and load a page on your site. Your visit should appear within a short time.
Later chapters cover Realtime, Tag Assistant, and DebugView in detail. For now, a quick check in the browser is enough. Open developer tools, go to the Network tab, and filter for collect. A request to google-analytics.com/g/collect with your ID in the tid parameter means the tag is sending hits. Ad blockers and privacy extensions can block this request, so test with them off.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| No data in Realtime | Wrong or mistyped Measurement ID | Compare the ID in the page with the one in the stream |
| No data, snippet visible in source | The `config` line is missing or has a syntax error | Check the browser console for script errors |
| No hits in Network tab, tag file loads | Consent default is denied and no update has been made | Check consent state and the banner's update call |
| Page views count twice | Snippet present along with a plugin or Tag Manager tag | Keep a single source for the same ID |
| Only some pages report | Snippet added to individual files, not a shared template | Move it to the template, or add it to the missing pages |
| Snippet appears in the page body as text | Pasted into a visual editor that escaped the tags | Use the platform's code injection field, not the content editor |
| Data from a development site mixes in | Same ID used on staging and production | Use a separate stream or property for each environment |
Edge cases
- Content Security Policy. A strict CSP can block both the
gtag.jsdownload and the inline script. You then need to allowgoogletagmanager.comandgoogle-analytics.comas sources, and permit the inline block through a nonce or hash. - Single-page applications. Enhanced measurement can detect history changes and record page views automatically, if the setting is on. If you also send manual
page_viewevents, setsend_page_view: falseor you risk duplicates. - Pages loaded in iframes. A tag inside an embedded frame treats that frame as its own page. Decide whether you want that before adding the snippet to embedded content.
- Multiple streams on one page. You can call
configmore than once with different IDs to send data to several streams. Do this deliberately, and not by accident through copied snippets. - Server-rendered caching. If a CDN caches pages, a template change may not reach visitors until the cache is purged.
Exercise
A page's source shows the Google tag snippet in the head, with the right Measurement ID, but a consent default of analytics_storage: 'denied' is placed after the gtag('config', ...) line. Why is this a problem, and what is the fix?
Show answer
The tag reads the consent state when config runs. With the default placed after config, the tag may already have sent data under the wrong state. Move the gtag('consent', 'default', {...}) call to after the gtag function definition and before gtag('js', ...) and gtag('config', ...). A consent banner can then change the state later with gtag('consent', 'update', {...}).
Exercise
You copy the snippet into a shared template and also keep a platform plugin that loads the same Measurement ID. Realtime shows two page views for every visit. What do you do?
Show answer
The same ID is being loaded twice, so each page_view is sent twice. Keep one source. Remove either the manual snippet or the plugin's setting, then reload a page and confirm in the page source and the Network tab that only one tag sends hits for that ID.