Sub topic 9
Implementing Events with gtag.js
Assume you have a GA4 web data stream, a Google tag installed on the site, and basic JavaScript knowledge. gtag.js is a JavaScript API that sends commands, including GA4 events, from your web page to Google Analytics.
How an event reaches GA4
An event call has two main parts:
- An event name, such as
loginorpurchase. - An object of parameters that adds context, such as the login method or purchase value.
The Google tag normally loads before your event code. It initializes the gtag function and identifies the destination property. Your event code then calls that function:
gtag('event', 'event_name', {
parameter_name: 'value'
});Use lowercase names with underscores. Choose the event name from GA4’s automatically collected or recommended events before creating a custom name.
Send a recommended event
Recommended events use names and parameter names that GA4 already understands. For example, a login event can include the recommended method parameter:
gtag('event', 'login', {
method: 'Google'
});For commerce, send the recommended purchase event with a transaction identifier, monetary values, and an items array:
gtag('event', 'purchase', {
transaction_id: 'T_12345',
value: 59.98,
currency: 'USD',
items: [
{
item_id: 'SKU_123',
item_name: 'Trail Shoes',
price: 29.99,
quantity: 2
}
]
});Use a unique transaction_id for each order. Reusing an identifier can cause duplicate purchase reporting. Keep numeric values numeric. For example, use 59.98, not the string '59.98'.
Send a custom event
Use a custom event only when no existing or recommended event describes the interaction. For example, a click that opens a newsletter form might use:
gtag('event', 'newsletter_signup_click', {
placement: 'footer',
plan_type: 'free'
});Place the call in the handler for the actual interaction:
document.querySelector('#newsletter-button').addEventListener('click', () => {
gtag('event', 'newsletter_signup_click', {
placement: 'footer',
plan_type: 'free'
});
});The selector must match an element on the page. If the element is created later, attach the handler after it exists or use event delegation.
Avoid duplicate sends
Send an event from one tracking path. If both a hard-coded gtag.js call and a Google Tag Manager GA4 event tag respond to the same click, GA4 may receive two events. Choose one implementation and document it.
Check the browser console for JavaScript errors, then use GA4 DebugView to confirm the event name and parameter values. DebugView is most useful when debug mode is enabled for the browser or the event is sent through a supported preview workflow.
Exercise
Which event should you send for a completed order, and which parameter should identify that order?
Show answer
Send the recommended purchase event and include a unique transaction_id parameter.