Generate Developer Portals

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

src/apimatic.json
{
  "portal": {
    "analytics": {
      "googleTagManager": { "containerId": "GTM-ABC123" },
      "googleAnalytics": { "measurementId": "G-ABC123" },
      "keepQueryParams": ["campaign_id"]
    }
  }
}
SettingWhat it is
googleTagManager.containerIdYour container's ID, as Google Tag Manager shows it.
googleTagManager.environmentThe auth and preview values of a Google Tag Manager environment, for a staging build. See Load a container's staging version.
googleAnalytics.measurementIdThe measurement ID of your GA4 web data stream.
googleConsentMode.defaultdenied, to start both Google tags in Google's Consent Mode on a portal with a consent banner. See Consent.
keepQueryParamsQuery 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

  1. Create a web data stream for your portal's address, and put its measurement ID in googleAnalytics.measurementId.
  2. 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_view for each page change, so with this setting on, every page change counts twice. apimatic portal generate and apimatic portal serve remind you whenever they load Google Analytics.
  3. 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_view for each page change. Two for each change means the setting in step 2 is still on.
  4. 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 asNames
Custom dimensionspicked_result, code_language, sdk_language, endpoint, status
Custom metricsresult_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 leave docs.search_term out of the container's search tag. With googleAnalytics set, 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 parameter send_page_view to false, or the first page counts twice.
  • Data Layer Variables. Create docs.page_location and docs.page_title. Every event's parameters sit under docs, and the portal clears docs before 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 parameters page_location and page_title from those variables, and a Custom Event trigger on docs_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_search reads docs.search_term, docs.picked_result, and docs.result_count.
  • Other tags. Any other tag that needs to know about a page change uses the docs_page_view trigger 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:

src/apimatic.json
{
  "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:

  1. Load it with portal.scripts.
  2. Turn on its option to read a Google Tag Manager data layer, so that it reads docs_page_view and the parameters under docs.
  3. 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-analytics

You 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.

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

src/apimatic.json
{
  "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 denied for ad_storage, ad_user_data, ad_personalization, and analytics_storage, with a wait_for_update of 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:

src/static/js/consent.js
(() => {
  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);
  };
})();
src/apimatic.json
{
  "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 defines gtag itself, as Google's own snippet does, so it doesn't depend on the portal having defined one.
  • The necessary category 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.scripts load, 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 googleTagManager and googleAnalytics unset. Once the reader agrees, load Google's tag from a script of your own, and pass it the portal's events from window.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 default of its own, Google uses that one, including its wait time. Give that default a wait_for_update too, 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.

EventParametersReported when
docs_page_viewpage_titleA page is shown: the first page, and each page the reader moves to.
docs_searchsearch_term, picked_result, result_countThe search dialog closes, if the reader typed a search or picked a result.
docs_code_copycode_languageThe reader selects the copy button of a code block.
docs_markdown_copyNoneThe Copy Markdown button copied the page.
docs_sdk_downloadsdk_languageThe reader selects a Download SDK link.
docs_api_requestendpoint, status, duration_msThe API playground shows the result of a request.
docs_plugin_installNoneThe reader selects the copy button of the install command on the Context Plugin page.
docs_not_foundpage_referrerThe not-found page is shown.

Event parameters

ParameterEventWhat it holds
page_locationEvery eventThe address of the page the event happened on. See Reported page addresses.
page_titledocs_page_viewThe page's title.
search_termdocs_searchWhat the reader typed, cut at 100 characters.
picked_resultdocs_searchThe address of the result the reader picked, without its # part, or empty when the reader picked none.
result_countdocs_searchHow many results the list showed.
code_languagedocs_code_copyThe ID of the code's language, such as python, json, or shellscript.
sdk_languagedocs_sdk_downloadThe SDK's language as languages names it in apimatic.json, such as csharp.
endpointdocs_api_requestThe method in capitals and the path as your API definition writes it, such as GET /users/{id}.
statusdocs_api_requestAlways text: the HTTP status as digits, such as 200, or client_error for a request that never reached the API.
duration_msdocs_api_requestHow long the request took, in milliseconds.
page_referrerdocs_not_foundThe 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_location is 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_install instead.
    • code_language is the language's ID, whichever name the code block was written with: ts and TypeScript are both reported as typescript, and bash and sh as shellscript.
    • 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_found and its own docs_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_ or hsa_.
  • _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/callback loads 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:

ToolMarker
PostHogph-no-capture
FullStoryfs-exclude
rrwebrr-block
Amplitudeamp-block
Hotjardata-hj-suppress
Microsoft Claritydata-clarity-mask
LogRocketdata-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:

src/apimatic.json
{
  "portal": {
    "seo": { "googleSiteVerification": "abc123" }
  }
}

Every page then carries the google-site-verification meta tag.

On this page