Sub topic 5
Recording actions as events
This chapter assumes you have read the chapters on UTM tagging and on installing GA4. You should have the gtag.js snippet running on your site, and you should be comfortable with basic JavaScript, such as event listeners and objects.
What an event is in GA4
GA4 records everything as an event. A page view is an event named page_view. A scroll is an event named scroll. A sign-up is an event you send yourself. Each event has a name and, optionally, a set of parameters that describe it.
This differs from older Universal Analytics, which had separate hit types for page views, events, and transactions. In GA4 there is one model, so one mental picture works for every action.
An event has three parts:
- Name: a short label such as
sign_up. It identifies the kind of action. - Parameters: key-value pairs that add detail, such as
method: 'email'orvalue: 25. - Context: data GA4 attaches on its own, such as the session's source and medium, the device, and the page location. You do not send these with each event.
The context is why events matter for social tracking. When a visitor arrives from a tagged Instagram link and later submits a form, GA4 joins the event to the session's source and medium. You can then ask which social channel produced sign-ups.
Four kinds of events
GA4 groups events by who sends them.
| Kind | Who sends it | Examples |
|---|---|---|
| Automatically collected | GA4 itself | `page_view`, `session_start`, `first_visit` |
| Enhanced measurement | GA4, if enabled in the data stream settings | `scroll`, `click` (outbound links), `file_download`, `video_start` |
| Recommended | You, using names Google defines | `sign_up`, `login`, `purchase`, `generate_lead` |
| Custom | You, using names you invent | `pricing_toggle`, `quiz_completed` |
Prefer a recommended event when one fits your action. Google's reports and ad integrations understand these names and their parameters. A custom event works, but you must build any reporting on it yourself.
Sending an event with gtag
The basic call has this shape: gtag('event', name, parameters). The example below sends the recommended sign_up event when a form is submitted.
document.querySelector('#signup-form').addEventListener('submit', function () {
gtag('event', 'sign_up', {
method: 'email'
});
});This code assumes the page already loaded the gtag.js snippet, so gtag exists, and that an element with the id signup-form is on the page. If the script runs before that element exists, querySelector returns null and the line throws an error. Place the script at the end of the body, or wrap it in a DOMContentLoaded listener.
Choosing the trigger
The trigger decides how accurate your count is. You have three common choices for a form:
- Submit event. Fires when the visitor submits, even if the server later rejects the data. It overcounts when validation fails.
- Button click. Fires earlier still, and also counts clicks on a disabled or invalid form.
- Thank-you page view. Fires only after the server accepted the submission. It is the most accurate, but only works if the form redirects to a distinct URL.
For a lead or sign-up that you will report to a client or optimize ad spend against, a confirmed success signal is better than a submit handler. If your form submits through JavaScript, fire the event inside the success callback of the request, not on the submit itself.
async function submitLead(formData) {
const response = await fetch('/api/lead', { method: 'POST', body: formData });
if (response.ok) {
gtag('event', 'generate_lead', {
value: 25,
currency: 'USD'
});
}
}Here the event fires only when the server answers with a success status. value and currency are a pair. If you send value without currency, GA4 will not use it in revenue reports.
Event parameters
Parameters turn a generic event into a useful one. Compare two events that mean the same thing:
gtag('event', 'generate_lead')records that a lead happened.gtag('event', 'generate_lead', { form_id: 'newsletter_footer', value: 25, currency: 'USD' })records which form and what a lead is worth.
Keep these rules in mind.
- Names are case-sensitive.
Sign_Upandsign_upare two different events. Use lowercase with underscores. - Names start with a letter. Use only letters, numbers, and underscores.
- Do not use reserved prefixes. Names starting with
google_,ga_, orfirebase_are reserved. - Limits exist. An event can carry up to 25 parameters, and event names are limited to 40 characters. Parameter values for standard properties are limited to 100 characters.
- Never send personal data. Do not put email addresses, names, or phone numbers in parameters. Google's terms prohibit it, and it creates privacy risk.
Parameters are not reports until you register them
This is the most common surprise. GA4 stores every parameter you send, but standard reports only show parameters that you register as custom dimensions (text) or custom metrics (numbers). To do this, open Admin, then Custom definitions, and create a dimension whose event parameter field matches the parameter name exactly, for example form_id.
Registration applies going forward only. Data sent before you registered the dimension will not appear in reports by that dimension. Register the parameters you plan to report on before you launch the campaign. Properties also have a limit on custom dimensions (50 event-scoped dimensions on a standard property), so register only what you will use.
Sending events through the data layer
Hard-coding gtag calls in page code means a developer must change the site for each new event. The alternative is to push events to the data layer and let a tag manager decide where they go. A later chapter covers this in depth. The basic push looks like this:
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
event: 'generate_lead',
form_id: 'newsletter_footer'
});The event key names the event. In Google Tag Manager, a custom event trigger listens for that name and fires a GA4 event tag. The page only reports what happened, and the tag manager decides what to do with it.
Pick one approach per event. If you both call gtag('event', ...) in the page and fire the same event from a tag manager, GA4 records it twice and your conversion counts double.
Carrying social context to later events
UTM values live in the landing URL's query string. When the visitor moves to another page, the query string is gone. GA4 itself remembers the source and medium for the session, so GA4 reports are fine. The problem appears when you want to store the UTM values yourself, for example in a hidden field so your CRM knows which post produced a lead.
The following script saves UTM values when a visitor lands.
const params = new URLSearchParams(window.location.search);
const keys = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term'];
const utm = {};
keys.forEach(function (k) {
if (params.get(k)) utm[k] = params.get(k);
});
if (Object.keys(utm).length > 0) {
sessionStorage.setItem('utm', JSON.stringify(utm));
}It only writes to storage when at least one UTM value is present. This prevents a later page without a query string from erasing the saved values. sessionStorage lasts for one browser tab, so a visitor who closes the tab and returns loses the values. Use localStorage if you need them longer, and check your consent rules first, because storing identifiers can require permission.
On the form page, read the value back and fill a hidden field:
const saved = JSON.parse(sessionStorage.getItem('utm') || '{}');
document.querySelector('#utm_source_field').value = saved.utm_source || '';How events flow
The diagram shows the path of one event from a user action to a report.
Common mistakes
- Duplicate events. The same action fires from page code and from a tag manager. Check one action at a time and count how many events arrive.
- Events on the wrong trigger. A submit handler fires on failed submissions. Fire on success.
- Inconsistent names.
signup,sign_up, andSignUpsplit one action across three rows. Write a short naming list and share it with everyone who adds tracking. - Unregistered parameters. The data is collected but cannot be used in standard reports.
- Sending events before consent. If you configured consent defaults to denied, events still send, but without cookies and with limited use. A later chapter covers this.
- Personal data in parameters. Remove it at the source.
Exercise
A visitor arrives from a tagged LinkedIn post and fills in your contact form. The form submits through JavaScript with fetch, and the server sometimes rejects entries with a 400 status. Where should you call gtag('event', 'generatelead', ...), and why? Also name one step you must take before you can report on a parameter such as formid in standard reports.
Show answer
Call it inside the branch that runs when the response is successful (for example, when response.ok is true), not in the submit handler. A submit handler fires even when the server rejects the entry, so it would count failed leads. Before reporting on form_id, register it as an event-scoped custom dimension in Admin under Custom definitions, using the exact parameter name. This only applies to data collected after registration.
Exercise
Your GA4 shows 200 generatelead events, but your CRM shows 100 leads. Your page code calls gtag('event', 'generatelead') and a Google Tag Manager tag also fires on a data layer event with the same name. What is the likely cause, and what do you change?
Show answer
The same action is being sent twice, once by the gtag call in the page and once by the tag manager tag, so each lead is counted twice. Keep only one method for this event. Remove either the gtag call or the tag manager tag, then confirm in DebugView that a single submission produces a single event.