Introduction
In this guide, I will show you how to send custom events to your Google Analytics 4 (GA4) property using the built-in JavaScript API (gtag.js). We will also cover how to verify these events and mark them as Conversions—the GA4 equivalent of “Goals”—within your dashboard.
Why Custom Events in GA4?
While GA4 includes “Enhanced Measurement” (which automatically tracks scrolls and basic clicks), it is still “blind” to many critical user interactions. If you are running a Single Page Application (SPA), using AJAX-driven forms, or want to track specific interactions like telephone link clicks, you need custom event tracking.
By using the gtag() function, we can send specific data packets to Google, allowing us to build a more accurate picture of user behavior.
Setting Up the GA4 Tracking Snippet
Before sending events, ensure the global tracking snippet is in your website’s <head>. In GA4, you find this under Admin > Data Streams > [Your Stream] > View tag instructions.
Pro Tip: Avoid using generic SEO plugins to “inject” this code if they restrict custom JavaScript. For the best control over technical SEO and entity tracking, adding this manually is the preferred method.
Handling Page Views in SPAs
In a Single Page Application (built with React, Vue, or Laravel Inertia), the browser doesn’t refresh when a user navigates. To track these as page views, we manually trigger an event.
First, disable automatic page views in your config to prevent double counting:
Then, trigger the view within your router’s navigation guard:
Tracking AJAX Form Submissions
If your forms submit without a page refresh, GA4 won’t see the conversion. You can trigger a custom form_submission event when the AJAX promise resolves successfully.
Note: I used generate_lead here because it is a GA4 Recommended Event.
Tracking Telephone and Email Clicks
To track “Click-to-Call” or “Click-to-Email” as conversions, we can loop through the links and attach listeners:
Contact Form 7 (WordPress) Integration
For WordPress developers using Contact Form 7, you can hook into their custom DOM event:
How to Turn Events into Conversions
In GA4, “Goals” are gone. Everything is an event. To track a “Goal”:
- Go to Admin > Events.
- Find your custom event (it may take 24 hours to appear).
- Toggle the switch Mark as conversion.
You can also see your events in real-time by going to Reports > Real-time.
Conclusion
Transitioning to GA4’s event-based model offers much more flexibility than the old Universal Analytics. By mastering the gtag() API, you ensure your data remains accurate as search engines move toward more complex, AI-driven user journeys.