How to set up GA4 events and key events with Claude Code
How to set up GA4 events and key events with Claude Code
Claude Code can do most of the work of GA4 event tracking that lives in your website's code. It can find every form, phone link and email link on the site, add the code that sends an event when each one is used, fire a generate_lead event only when a form submission actually succeeds, and help you test that the events arrive. The parts that live in Google Analytics are yours: deciding what counts as a lead, marking events as key events in the GA4 admin, and checking the reports.
This guide walks through the job step by step, as of October 2026: a tracking plan, the code, testing in DebugView, marking key events, and the one rule that matters most for server-side events. The Measurement Protocol secret never goes in your site's front-end code.
Key Takeaways
- An event measures "a specific interaction or occurrence on your website or app". Google says "Any event you collect can become a key event."
- Google's recommended event for leads is generate_lead, defined as when a user "submits a form or a request for information".
- Standard GA4 properties can mark up to 30 events as key events (50 on Analytics 360). Marking one counts from that point forward and "doesn't change historic data".
- For thank-you pages, don't mark page_view as a key event. Create a new event from page_view with the thank-you URL instead.
- Test with DebugView, which needs debug mode turned on, for example through Google Tag Assistant.
- Google says the Measurement Protocol "api_secret is private. Don't expose it in the client-side code of your website or app."
Events and key events in plain English
GA4 records events: page views, scrolls, clicks, form submissions. Some arrive automatically or through enhanced measurement, a setting that collects common interactions such as form starts and submissions. Others are recommended events with names Google defines, such as generate_lead. The rest are custom events you name yourself. Google notes that "Custom events don't show up in most standard reports", so use a recommended name when one fits.
A key event is an event you've told GA4 matters to the business, such as a lead or a purchase. Key events are the numbers you watch in reports. Picking them is a business decision, not a coding task.
Step 1: write a tracking plan
A tracking plan is a short table that says what you measure and why. Write it before any code, and agree it with whoever reads the reports.
| Visitor action | Event name | When it fires | Key event? |
|---|---|---|---|
| Submits the contact form successfully | generate_lead (recommended) | After the server confirms the submission was received | Yes |
| Taps a phone number | A custom name, such as phone_click | On click of any tel: link | Your call |
| Clicks an email address | A custom name, such as email_click | On click of any mailto: link | Usually no |
| Books an appointment through an embedded tool | Depends on the tool | On the tool's confirmation, if it exposes one | Yes |
The event names in the phone and email rows are examples, not Google's names. Whatever you choose, use the same name everywhere and write it down.
Step 2: let Claude Code inventory the site
Example prompt: Use plan mode. Find every form, every tel: link and every mailto: link in the site's templates and content. For each form, tell me where it submits, how the page knows the submission succeeded, and whether any analytics code already fires. Also tell me how GA4 is installed: gtag.js directly or Google Tag Manager. Don't change anything.
This report often turns up surprises: a form in a popup nobody remembered, an old tracking snippet still loading, or a form that shows "thank you" even when the send fails. Fix the last one first. Our guide to building and fixing contact forms with Claude Code covers that.
A person reviews: the inventory against the tracking plan. Every row in the plan should map to something real on the site.
Step 3: choose gtag.js or Tag Manager
If the site loads gtag.js directly, Claude Code adds event calls in the code. If the site uses Google Tag Manager, Google describes it as a system "that allows you to set up and manage tags on your site without changing your website's code" once its two snippets are on each page. Tags, triggers and variables live in a "container" in the Tag Manager interface.
With Tag Manager, a common split is that Claude Code adds code that signals each action from the site, and a person configures the matching tags and triggers in the container. Either way, don't run both setups for the same event, or every lead counts twice.
Step 4: fire the lead event on success, not on click
The most common tracking mistake is firing a lead event when someone clicks Submit. If validation fails, the server errors or a spam filter rejects the message, you've recorded a lead that never arrived. Fire generate_lead only after the server responds that the submission was accepted.
Example prompt: In the contact form handler, send a GA4 generate_lead event only after the server returns success. Don't send it on errors or validation failures. Don't include the visitor's name, email, phone number or message in any event parameter. Show me the diff before applying.
On a gtag.js site, the call itself is short:
gtag('event', 'generate_lead');
Two more rules belong in the same prompt:
- No personal information. Google's policies "mandate that no data be passed to Google that Google could use or recognize as personally identifiable information (PII)", including "email addresses, personal mobile numbers, and social security numbers." Watch URLs too: a form that puts the email address in the thank-you page URL leaks it into page_view.
- No double counting. Enhanced measurement can already send form_submit "when the user submits a form". That's useful for comparing starts with submissions, but it isn't the same as a confirmed lead. Mark only one event per lead as a key event.
If your form sends people to a thank-you page instead, you don't need code at all. Google's guidance is to use "+ Create event", base it on page_view, and enter the thank-you URL. Don't mark page_view itself as a key event, "since all pageviews will then count as key events", and "avoid modifying the page_view event".
Step 5: test in DebugView
DebugView "displays the events and user properties that Analytics collects from a user in real time". "You must enable debug mode to use DebugView." For your own device, Google suggests "the Google Tag Assistant through tagassistant.google.com or preview mode". On gtag.js you can add a debug_mode parameter, but remove it when you're done: Google notes that setting it to false doesn't turn debug mode off.
- Turn on debug mode for your own browser with Tag Assistant.
- Submit the form with test details, and tap a phone link.
- Confirm in DebugView that generate_lead arrives once per successful submission, with no personal data in its parameters.
- Submit the form with a deliberate error, and confirm no lead event arrives.
If nothing shows up, check consent first. Google says events "are not visible in debug mode" if you use client-side privacy controls, or consent mode without consent for Analytics cookies. Claude Code can also open the page in Chrome through its Chrome integration and read the console for errors. Our pre-deploy QA routine includes a tracking check like this one.
Step 6: mark key events in GA4
This step happens in Google Analytics, not in code. Google's instructions: "In Admin, under Data display, click Events" and click "the star icon" next to the event. Allow "up to 24 hours" for it to show in standard reports. Marking an event "affects reports from time of creation", so set it up before a campaign starts, not after.
Google's help page is inconsistent about the role you need. Its "Before you begin" note and the steps for creating a new key event say Marketer or above, while the steps for starring an existing event say "Editor or above". Google's roles page says the Marketer role "Can create, edit, and delete audiences, events, and key events". If you can't mark the event, ask the property's administrator. Remember the limit: up to 30 key events on a standard property.
Server-side events and the api_secret
Some leads happen away from the browser: a booking confirmed in your CRM, or a call answered by a tracking system. Google's Measurement Protocol lets a server send those events. Google says it is meant "to augment automatic collection through gtag, Tag Manager, and Google Analytics for Firebase, not to replace it," so the site still needs its normal tag. Google also says it has "reached a mature, finalized product state" and recommends the Data Manager API for new server-to-server work, so check which one suits a new project.
The Measurement Protocol needs an api_secret, and Google is explicit: "The api_secret is private. Don't expose it in the client-side code of your website or app." Exposing it "allows unauthorized parties to send arbitrary or spam data to your Google Analytics property". In practice:
- The secret lives in an environment variable on the server or host, never in a JavaScript file a browser downloads.
- It never goes into a prompt, a CLAUDE.md file or a committed file. Claude Code can write code that reads the variable without ever seeing its value.
- Add a deny rule such as Read(./.env) so Claude Code's file tools and common file commands can't open your environment file. Anthropic's permissions docs note that such rules don't cover a script that reads files indirectly, so keeping the secret out of the project matters more than the rule.
Our guide to keeping secrets away from Claude Code covers this in detail.
Reading the data back
Once events flow, Claude Code can help you read them. Google publishes a Google Analytics MCP server that is "available for read requests only"; its GitHub repository labels it "Experimental". It needs read-only credentials that you set up. Our overview of MCP servers for website teams explains connecting it, and our Claude data analytics setup guide covers reporting for small businesses. Treat any summary as a starting point, and check the numbers in GA4 itself before you act on them.
Conclusion
Good GA4 tracking starts with a plan people agree on, then code that fires each event once, at the right moment, with no personal data. Claude Code is fast at the inventory, the code and the testing. People choose the key events, mark them in GA4 and own the secrets. For the SEO side of analytics, see our guide to Claude Code for technical SEO. If you'd like the tracking built for you, see our Claude Code development services. More guides are in our Claude Code Guide.
Frequently asked questions
Can Claude Code mark key events for me?
Not through your site's code. Marking a key event is a setting in the GA4 admin, done by someone with the right role. Claude Code can write the steps for you to follow, but a person should make the change and check the result.
Why don't my events show in reports yet?
Google allows up to 24 hours for a newly marked key event to show in standard reports. Use DebugView or realtime reports to confirm events arrive while you wait.
Is it safe to put the GA4 measurement ID in my site's code?
The measurement ID used by gtag.js is part of the normal front-end setup. The Measurement Protocol api_secret is different: Google says it is private and must not be exposed in client-side code.
Should a phone click count as a lead?
It depends on your business. A tap on a phone link shows intent, not a completed call. Some businesses mark it as a key event, and others track calls through a call-tracking system. Decide, write it in the tracking plan, and be consistent.
Can I track what people type into my form?
Don't send what they type to Google Analytics. Google's policies prohibit sending data it could recognize as personally identifiable information, and laws vary by location. If in doubt, Google's own advice is to consult an attorney.
Put this into action with eSEOspace
We help businesses grow with seo, geo & aeo that actually performs. Explore the services behind this guide:
Get a FREE Audit
We'll perform a comprehensive SEO, AEO, GEO & CRO audit of your website — completely free — and show you exactly how to outrank your competitors.
Don't have a site yet? Get in touch →
Get a FREE GEO/AEO/SEO Audit
We'll analyze your site's SEO, GEO, AEO & CRO — completely free — and show you exactly how to get found across Google and AI answers.
Don't have a site yet? Get in touch →
Great — your audit is on the way!
We'll send your free SEO/GEO/AEO/CRO audit within the next few hours. Where should we send it?
You're all set! ✓
Your free audit is being prepared — check your inbox in the next few hours. Talk soon!
On this page
- Key Takeaways
- Events and key events in plain English
- Step 1: write a tracking plan
- Step 2: let Claude Code inventory the site
- Step 3: choose gtag.js or Tag Manager
- Step 4: fire the lead event on success, not on click
- Step 5: test in DebugView
- Step 6: mark key events in GA4
- Server-side events and the api_secret
- Reading the data back
- Conclusion
- Frequently asked questions





