Set Up Analytics
Load Google Tag Manager and Google Analytics 4 on your developer portal, and see the events the portal reports to them.
Your developer portal can load Google Tag Manager and Google Analytics 4 (GA4), and it reports its own page views, searches, and other events to both. You set this up under portal.analytics in src/apimatic.json. Every setting is optional: set Google Tag Manager, GA4, both, or neither.
To load another vendor's script, or to pass the portal's events to another tool, see Add Custom Scripts.
Add your IDs
{
"portal": {
"analytics": {
"googleTagManager": { "containerId": "GTM-ABC123" },
"googleAnalytics": { "measurementId": "G-ABC123" },
"keepQueryParams": ["campaign_id"]
}
}
}| Setting | What it is |
|---|---|
googleTagManager.containerId | Your container's ID, as Google Tag Manager shows it. |
googleTagManager.environment | The auth and preview values of a Google Tag Manager environment, for a staging build. See Load a container's staging version. |
googleAnalytics.measurementId | The measurement ID of your GA4 web data stream. |
googleConsentMode.default | denied, to start both Google tags in Google's Consent Mode on a portal with a consent banner. See Consent. |
keepQueryParams | Query parameters of your own to keep in the page addresses the portal reports. See Reported page addresses. |
Paste each ID as Google shows it. The CLI checks that an ID is present and not blank, and nothing else. A mistyped ID still builds, and the tag then doesn't work in the browser.
The portal adds the tags from its own code when a page starts. They aren't in the page's HTML source, so a checker that reads only the HTML doesn't find them. Google's Tag Assistant does.
For each property's type, see portal.analytics in the apimatic.json reference.
Set up Google Analytics 4
- Create a web data stream for your portal's address, and put its measurement ID in
googleAnalytics.measurementId. - Turn off the stream's own page-change tracking. In GA4, go to Admin > Data streams > your stream > Enhanced measurement, open the advanced settings under Page views, and clear Page changes based on browser history events. The portal already sends a
page_viewfor each page change, so with this setting on, every page change counts twice.apimatic portal generateandapimatic portal serveremind you whenever they load Google Analytics. - Check the result. Open the portal with Google's Tag Assistant, so that DebugView in GA4 shows your session, and move between pages. DebugView must show one
page_viewfor each page change. Two for each change means the setting in step 2 is still on. - Don't also add a GA4 tag for this stream to your Google Tag Manager container, or every hit counts twice.
Register the parameters in GA4
GA4 reports a custom parameter only after you register it under Admin > Custom definitions.
| Register as | Names |
|---|---|
| Custom dimensions | picked_result, code_language, sdk_language, endpoint, status |
| Custom metrics | result_count, duration_ms |
A new definition can take a day or two to appear in reports. page_title, page_location, page_referrer, and search_term are GA4's own parameters and need no registration.
Search terms and personal data
search_term is what the reader typed. Readers sometimes paste an email address or an API key into a search box, and Google's terms don't allow personal data in Analytics.
- Keep email redaction on in the stream's Redact data settings.
- If your readers' searches can hold other sensitive data, such as API keys, load GA4 through your Google Tag Manager container instead of
googleAnalytics, and leavedocs.search_termout of the container'ssearchtag. WithgoogleAnalyticsset, the portal always sends the term.
Set up Google Tag Manager
Your container gets the portal's events as data layer pushes, so the usual Google Tag Manager setup applies:
- Google tag. Fire it on the Initialization - All Pages trigger, so that it's ready before the first
docs_page_view. Set its configuration parametersend_page_viewtofalse, or the first page counts twice. - Data Layer Variables. Create
docs.page_locationanddocs.page_title. Every event's parameters sit underdocs, and the portal clearsdocsbefore each event, so a variable never holds a value from the previous event. - GA4 Event tag for page views. Use the event name
page_view, the parameterspage_locationandpage_titlefrom those variables, and a Custom Event trigger ondocs_page_view. - Other events. Follow the same pattern: a Custom Event trigger on the event's name, and a Data Layer Variable for each parameter. For example, a tag for
docs_searchreadsdocs.search_term,docs.picked_result, anddocs.result_count. - Other tags. Any other tag that needs to know about a page change uses the
docs_page_viewtrigger the same way. - Your GA4 stream. When the container sends to GA4, also follow step 2 of Set up Google Analytics 4.
Load a container's staging version
To check a staging build in Google Tag Manager, have it load one of the container's environments:
{
"portal": {
"analytics": {
"googleTagManager": {
"containerId": "GTM-ABC123",
"environment": { "auth": "aBcDeF123", "preview": "env-3" }
}
}
}
}auth and preview are the gtm_auth and gtm_preview values from the environment's snippet in Google Tag Manager (Admin > Environments > Actions > Get Snippet).
Leave environment out of your production portal. Both values are public in the built portal, as they are in Google's own snippet. Anyone who has them can load that environment's version of the container, unpublished tags included.
Access to your container
Access to your Google Tag Manager container is access to your portal's code. Anyone who can publish the container can run any script on every page, without a rebuild, and read what readers type. Give access only to people you'd give the repository to.
Use another tag manager
The portal writes its events to window.dataLayer in Google Tag Manager's format, whether or not a Google tag is set. To use another tag manager:
- Load it with
portal.scripts. - Turn on its option to read a Google Tag Manager data layer, so that it reads
docs_page_viewand the parameters underdocs. - Turn off its own page-change tracking, or page changes count twice.
A tool that doesn't read a data layer can get the same events from window.apimatic.analytics.subscribe().
Previews and staging builds
apimatic portal serve loads the same tags as your hosted portal, so the page views of your preview count like anyone else's. To keep them out of your reports, run the preview without analytics:
apimatic portal serve --no-analyticsYou can also define your own addresses as internal traffic in GA4 (Admin > Data streams > your stream > Configure tag settings > Define internal traffic) and filter that traffic out of your reports.
For a staging site that must not count, build the portal the same way:
apimatic portal generate --no-analytics--no-analytics leaves out the tags set in portal.analytics. It also leaves out the analytics and marketing scripts in portal.scripts, and sends no events to the scripts that stay or to window.dataLayer. See Leave scripts out of previews and staging builds.
The portal still writes one thing to window.dataLayer: the consent default from googleConsentMode. That way, a Google tag that a kept script loads still starts as denied.
Consent
The portal doesn't ask readers for consent. Implementing consent is your responsibility, under the laws and regulations that apply to your portal. Use a consent tool of your own, as a script in portal.scripts or as a tag in your Google Tag Manager container. The portal's part is googleConsentMode: it starts the Google tags as denied until your tool reports the reader's answer.
Start the Google tags as denied
{
"portal": {
"analytics": {
"googleAnalytics": { "measurementId": "G-ABC123" },
"googleConsentMode": { "default": "denied" }
}
}
}denied is the only value of default. With it, the portal turns on Google's Consent Mode before it sets up either Google tag:
- It queues a consent default of
deniedforad_storage,ad_user_data,ad_personalization, andanalytics_storage, with await_for_updateof 500 milliseconds. - Both tags still load at once. Until your consent tool reports an answer, they set no cookies and mark every hit as denied. Google calls this advanced consent mode.
- Once your tool calls
gtag('consent', 'update', ...), the tags follow the reader's answer.
Set googleConsentMode whenever a consent banner decides what's tracked. Without it, the Google tags can set their cookies and send the first page view before your consent tool has run.
Report the reader's answer
Most consent tools that support Google's Consent Mode make the update call themselves. Follow your tool's own guide for Consent Mode.
A banner of your own makes the call from a file you list in portal.scripts:
(() => {
window.dataLayer = window.dataLayer || [];
function gtag() {
window.dataLayer.push(arguments);
}
function report(answer) {
gtag('consent', 'update', {
ad_storage: answer,
ad_user_data: answer,
ad_personalization: answer,
analytics_storage: answer
});
}
// A reader who answered on an earlier visit.
const stored = localStorage.getItem('consent');
if (stored !== null) report(stored);
// Your banner calls this with 'granted' or 'denied' when the reader answers.
window.saveConsent = (answer) => {
localStorage.setItem('consent', answer);
report(answer);
};
})();{
"portal": {
"scripts": [
{ "src": "static/js/consent.js", "category": "necessary" }
]
}
}- Returning readers. The file reports a stored answer as soon as it runs. The portal's default waits up to 500 milliseconds for that call, so a returning reader's first page view is sent with their answer.
- Its own
gtag. The file definesgtagitself, as Google's own snippet does, so it doesn't depend on the portal having defined one. - The
necessarycategory keeps the file in a build made with--no-analytics. See Categories.
What googleConsentMode doesn't do
- It shows no banner and stores no answer. Your consent tool does both.
- It doesn't affect which scripts in
portal.scriptsload, or when. Every listed script loads for every reader, whatever its category. See Categories. - It doesn't keep the Google tags from loading. If no Google tag may load before the reader agrees, leave
googleTagManagerandgoogleAnalyticsunset. Once the reader agrees, load Google's tag from a script of your own, and pass it the portal's events fromwindow.apimatic.analytics.subscribe(), which also delivers earlier events. - It doesn't cover other vendors' tags in your container. A custom HTML tag in your container, such as an advertising pixel, follows Consent Mode only if you add consent checks to it in the container.
- It doesn't override your consent tool's own default. If your tool sets a consent
defaultof its own, Google uses that one, including its wait time. Give that default await_for_updatetoo, or a returning reader's first page view can be sent as denied.
Events the portal reports
The portal reports eight events. It writes each one to window.dataLayer, the queue both Google tags read, whether or not a Google tag is set. With --no-analytics, it writes none.
| Event | Parameters | Reported when |
|---|---|---|
docs_page_view | page_title | A page is shown: the first page, and each page the reader moves to. |
docs_search | search_term, picked_result, result_count | The search dialog closes, if the reader typed a search or picked a result. |
docs_code_copy | code_language | The reader selects the copy button of a code block. |
docs_markdown_copy | None | The Copy Markdown button copied the page. |
docs_sdk_download | sdk_language | The reader selects a Download SDK link. |
docs_api_request | endpoint, status, duration_ms | The API playground shows the result of a request. |
docs_plugin_install | None | The reader selects the copy button of the install command on the Context Plugin page. |
docs_not_found | page_referrer | The not-found page is shown. |
Event parameters
| Parameter | Event | What it holds |
|---|---|---|
page_location | Every event | The address of the page the event happened on. See Reported page addresses. |
page_title | docs_page_view | The page's title. |
search_term | docs_search | What the reader typed, cut at 100 characters. |
picked_result | docs_search | The address of the result the reader picked, without its # part, or empty when the reader picked none. |
result_count | docs_search | How many results the list showed. |
code_language | docs_code_copy | The ID of the code's language, such as python, json, or shellscript. |
sdk_language | docs_sdk_download | The SDK's language as languages names it in apimatic.json, such as csharp. |
endpoint | docs_api_request | The method in capitals and the path as your API definition writes it, such as GET /users/{id}. |
status | docs_api_request | Always text: the HTTP status as digits, such as 200, or client_error for a request that never reached the API. |
duration_ms | docs_api_request | How long the request took, in milliseconds. |
page_referrer | docs_not_found | The portal page the reader came from. On a first load, it's the browser's referrer without its query string, or empty when the browser sends none. |
A few things to know about when events are reported:
- Page views. A change to only the
#part of the address, or to query parameters the portal drops, isn't a new page view. - Searches.
page_locationis the page the search was made on, not the result's page. - Code copies. The event covers code blocks on your pages, in the API reference and its example responses, and in the playground. It also covers the install command on an SDK card. The install command on the Context Plugin page reports
docs_plugin_installinstead.code_languageis the language's ID, whichever name the code block was written with:tsandTypeScriptare both reported astypescript, andbashandshasshellscript.- A language the portal doesn't know is reported by the name it was written with, in lowercase. A block with no language is
plaintext.
- SDK downloads. The event covers the Download SDK links on the SDKs page and on each SDK's own page.
- API requests. The event never carries the request's address, headers, or body. Those hold what the reader typed, API keys included.
- Missing pages. A missing page reports
docs_not_foundand its owndocs_page_view.
What the portal writes to the data layer
For each event, the portal pushes two entries to window.dataLayer. The first clears the previous event's parameters. The second is the event, with its parameters under one docs key:
{ docs: null }
{ event: 'docs_page_view', docs: { page_title: 'Quickstart | Acme API', page_location: 'https://docs.acme.com/guides/quickstart' } }What Google Analytics 4 receives
With googleAnalytics set, the portal also sends each event to GA4 directly, under its name without the docs_ prefix. docs_page_view arrives as page_view and docs_search as search, which are GA4's own event names. docs_code_copy arrives as code_copy, and so on.
Reported page addresses
A reported page address leaves out the page's # part and its query string. It keeps the query parameters that ad and email platforms read from the address:
- Parameters that start with
utm_orhsa_. _gl,gclid,gbraid,wbraid,gad_source,dclid,fbclid,msclkid,ttclid,twclid,li_fat_id,mc_cid,_hsenc, and_hsmi.
With googleAnalytics set, GA4's own events, such as scrolls and file downloads, use the same address.
keepQueryParams adds names of your own to that list. The built-in names always stay. Add a parameter your own links use, such as a ref for referral codes. Each kept parameter makes one page count as several addresses in your reports, so keep only the names you need.
Sign-in responses
When your API uses OAuth 2.0, the playground's sign-in sends the reader to your provider. The provider sends them back to the portal's /oauth/callback page, with its response in that page's address, for example ?code=...&state=.... The portal keeps the response out of every address it reports and every address a tag sees:
- The page at
/oauth/callbackloads no tag and no listed script, reports no event, and sends no referrer. - That page passes the response to the playground through the browser tab's session storage, then sends the reader back to the page they started from. No other page's address holds the response.
Session storage is open to every script on a page. The response waits there until the playground reads it, and the playground keeps the reader's token there for as long as the tab stays open. A script in portal.scripts, or a custom tag in your container, can read both. See the warning on Add Custom Scripts and Access to your container.
Session replay tools
Session replay tools record what readers type, and in the API playground readers type keys and tokens. The portal puts each tool's opt-out marker on the playground, so these tools leave it out of recordings:
| Tool | Marker |
|---|---|
| PostHog | ph-no-capture |
| FullStory | fs-exclude |
| rrweb | rr-block |
| Amplitude | amp-block |
| Hotjar | data-hj-suppress |
| Microsoft Clarity | data-clarity-mask |
| LogRocket | data-private |
For a tool not in the table, block the selector [data-private] in its settings. The markers are on the playground on the endpoint page, the dialog it opens, and the cURL sample beside it, which shows what the reader types.
The markers hide what's on screen and nothing else. A replay or monitoring tool that also records network requests still captures the playground's requests, with their Authorization header and the response bodies. Turn that recording off for the portal, or leave your API's host out of it, in the tool's own settings.
Content Security Policy
If your portal's host sets a Content Security Policy, allow the sources that Google's CSP guide lists for Google Tag Manager and Google Analytics 4, and whatever each tag inside your container loads.
Verify your site for Google Search Console
Verify your portal's domain as a Domain property, with the DNS TXT record Search Console gives you. That needs nothing in the portal.
For a URL-prefix property that you verify with the HTML tag method, put the tag's content value in portal.seo.googleSiteVerification:
{
"portal": {
"seo": { "googleSiteVerification": "abc123" }
}
}Every page then carries the google-site-verification meta tag.