Skip to content

feat(docs-next): send docs search and product-switch events to the data layer - #423

Merged
nickvigilante merged 4 commits into
mainfrom
vigilante/docs-datalayer-events
Dec 3, 2026
Merged

nickvigilante merged 4 commits into
mainfrom
vigilante/docs-datalayer-events

Conversation

@nickvigilante

Copy link
Copy Markdown
Collaborator

Merge order

This needs no Security sign-off, because it adds no script origin, no CSP change and no vendor. It can merge at any time: the events are inert until Marketing adds Tag Manager triggers for the two new event names (listed below), so the events are only useful after that. #288 rewrites the "Show more matches" expander in packages/docs-next/src/hybrid-search.tsx, the same file this touches. My change there is two lines (a hook call and an onSelect prop), so whichever lands second should rebase cleanly.

Summary

The docs now push two custom events to the Google Tag Manager dataLayer, so Segment, GA4 or any tag Marketing adds to GTM-NLLNT3K can read them. docs_search fires once per search session, when the search dialog closes after the reader typed a query of two or more characters, with search_term, results_count, product and result_opened. docs_product_switch fires when a reader picks a different product in the sidebar switcher, with from_product and to_product. Page views are not part of this: Marketing needs a history-change trigger in the container.

Marketing needs a Custom Event trigger for docs_search and one for docs_product_switch, and a tag per destination reading the fields above as Data Layer Variables.

Privacy decision for review: search queries are sent to the data layer after marketing consent, trimmed, whitespace-collapsed and capped at 100 characters, because readers can paste error messages with hostnames or tokens. No result URL is sent. Security and Privacy should review that before Marketing wires docs_search to Segment.

Design

trackDocsEvent(event, data) in @coder/docs-config/client (new track.ts) pushes { event, ...data } onto window.dataLayer only when window.google_tag_manager["GTM-NLLNT3K"] exists. GTM replays whatever is already in dataLayer when it loads, so an event pushed before consent would be sent after a later accept; when the container is absent (flag off, previews, offline export, reader denied, GTM not yet loaded) the event is dropped and not queued. Withdrawing marketing consent reloads the page, so no extra handling is needed. The helper has no imports beyond analytics.ts and json.ts, so the client entry stays zod-free.

useSearchEvent (new search-events.ts) is used by both DocsSearchDialog and HybridSearchDialog. It watches the dialog's open prop, remembers the query the dialog opened with, and on close sends the event if the query changed during the session and is at least two characters. Closing by Escape, the overlay, the close button or choosing a result all go through the same close, and the "Show more matches" expander does not affect open. Choosing a result marks result_opened through the dialog's onSelect, which runs in the same batch as the close. countResults moved into the same file, and results_count is 0 when the closing query's results had not arrived. A reader who reopens the dialog with the old query and closes it without changing it sends nothing more, and one who chooses a result for the carried-over query without typing is not counted.

The switcher sends docs_product_switch from the option's click handler, with product ids from productForUrl so they match the search event's product. Choosing the current product sends nothing.

QA

These steps need a build with DOCS_ANALYTICS=1; the PR preview does not set it, so I could not verify them in a browser, only through the jsdom tests below. To check on a deployment with the flag on:

  1. Open any docs page in Chrome or Firefox, accept all cookies in the Osano banner (marketing included), and wait a couple of seconds for Tag Manager to load.
  2. Open the console (Chrome: Ctrl+Shift+J, Firefox: Ctrl+Shift+K) and run dataLayer.filter(e => e.event && e.event.startsWith("docs_")). It starts empty.
  3. Open search (Ctrl+K), type "workspace", close it with Escape, and run the same line: one docs_search entry with search_term: "workspace", a results_count, product: "coder" and result_opened: false.
  4. Search again and press Enter on a result: a second entry with result_opened: true.
  5. On the Coder docs, open the product switcher in the sidebar and pick code-server: a docs_product_switch entry with from_product: "coder" and to_product: "code-server". Picking the product you are already on adds nothing.
  6. Clear site data, reload, deny marketing cookies, repeat steps 3 and 5: dataLayer holds no docs_* entry.

Pages to compare

There is nothing to see on the page: no layout or visible change. The check is in the console, as above.

What to check Production Preview
Console dataLayer after search (needs DOCS_ANALYTICS, so expect no events on the preview) https://coder.com/docs/ the branch alias from the docs preview status (Vercel login needed)

Testing

New tests, each confirmed to fail without the change: track.test.ts (nothing without the container, for another container or without a data layer; the exact object with it), search-events.test.tsx (both dialogs, rendered into jsdom: a single docs_search push on close with exact fields, the product, result_opened true on choosing a result, truncation to 100 characters with collapsed whitespace, no event under two characters or without a query, none on reopen without a new query, none without the container), and product-switcher.test.tsx (the docs_product_switch fields, none for the current product, none without the container). Package build, typecheck, lint and tests for docs-config and docs-next pass, pnpm --filter @coder/docs-site first-load:check passes (no forbidden libraries), and the offline export builds and pnpm --filter @coder/offlinedocs analytics:check passes (6 pages, none carry analytics).

Upstream

No. This is our own analytics wiring around our own consent setup, not a generic Fumadocs bug or option.

https://linear.app/codercom/issue/DOCS-1917


🤖 Built with AI assistance.

…ta layer

The docs sent no custom events, so Marketing could not report on search or product use.
A docs_search event now fires once per search session, when the dialog closes after a query of two or more characters, and docs_product_switch fires when a reader picks another product.
trackDocsEvent pushes only once the Tag Manager container is on the page and otherwise drops the event, because the container replays whatever is queued when it loads, which would send an event from before consent.
The search term is whitespace-collapsed, trimmed and capped at 100 characters, and no result URL is sent.

Assisted-by: AI
@linear-code

linear-code Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
DOCS-1917 Send docs search and product-switch events to the data layer, for Segment

Nick and Cedric agreed to leave docs search alone and use Segment for statistics instead.

The docs already load coder.com's consent manager (Osano) and Google Tag Manager (GTM-NLLNT3K) behind DOCS_ANALYTICS. They send no custom events. The closed HockeyStack search-goal work (#340) was the last attempt.

What to build first. Push a small set of events to the Tag Manager dataLayer. Segment, GA4 or any other tag Marketing adds to the container can then read them. This needs no new vendor origin, so no CSP change and no Security sign-off.

Starting events.

  • docs_search: one event per search session, with the final query, the result count, the reader's product, and whether they opened a result.
  • docs_product_switch: the product a reader switched from and to.
  • Page views are Marketing's to configure in the container. The docs navigate on the client, so the container needs a history-change trigger.

Consent. Tag Manager loads only after a reader accepts marketing consent, and it replays anything already in the dataLayer. An event pushed before consent would be sent after the reader accepts later. Push events only once the container has loaded. A reader who denies sends nothing.

Privacy. Search queries can hold pasted text, such as error messages with tokens or hostnames. Trim the query, cap its length, and say so in the PR so Security and Privacy can review it.

Needs from Marketing. Tag Manager triggers and tags for the new event names, and a Segment tag if Segment is used. Check whether coder.com already sends Segment events through this container.

Done when.

  • The events reach window.dataLayer only after the container has loaded.
  • Nothing is pushed before consent, or when DOCS_ANALYTICS is off, or in the offline export.
  • Tests render the search dialog and the product switcher and assert the pushes.
  • The PR says which event names Marketing needs to wire up.

+++ Agent notes

  • Consent bootstrap and Tag Manager loading: consentBootstrapScript in packages/docs-config/src/analytics.ts. Its loaded flag is private to the closure, so gate on the container being present, for example window.google_tag_manager?.["GTM-NLLNT3K"].
  • coder.com-new pushes events with track(event, data) in packages/ui/lib/track.ts. Its event names are the ones the container's triggers listen for.
  • New vendor origins go in ANALYTICS_SCRIPT_ORIGINS (engine) and TRACKING_HOSTS (coder.com-new), and need Security sign-off. Not needed for this issue.

+++

Review in Linear

@nickvigilante
nickvigilante marked this pull request as ready for review November 30, 2026 19:25
@nickvigilante
nickvigilante requested a review from a team as a code owner November 30, 2026 19:25

@Jesswinters Jesswinters left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The consent gating is well done. trackDocsEvent checks for the loaded container instead of queueing onto dataLayer, which avoids GTM replaying pre-consent events. useSearchEvent is shared by both dialogs and fires once per session. The tests render the real dialogs and assert exact payloads. I checked the fumadocs SearchDialog select path (onOpenChange(false) then onSelectProp, in the same handler), so result_opened is set before the close effect runs. The productForUrl ids also hold, because the switcher only renders on the latest version at /.

No blocking issues. 1 P2 and 1 nit across 2 inline comments.

Generated by Coder Agents on behalf of @Jesswinters.

if (final.search === session.current.startedWith || term.length < SEARCH_TERM_MIN_LENGTH)
return;
trackDocsEvent("docs_search", {
search_term: term,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 search_term may reach third parties as soon as this merges, not only after Marketing adds a trigger.

The PR says the events are inert until Marketing adds Custom Event triggers, and that Security and Privacy should review search_term before it goes to Segment. That only holds if no tag in GTM-NLLNT3K already fires on all custom events (for example a .* regex trigger or an "All Custom Events" trigger), and no vendor script reads dataLayer by itself. Several of the tags in ANALYTICS_SCRIPT_ORIGINS (HockeyStack, Dreamdata, 6sense, Hotjar) are the kind that can auto-capture dataLayer pushes. In that case pasted error messages, hostnames or tokens, capped at 100 characters, go to those vendors without the review the PR asks for.

Could someone with container access confirm there are no catch-all triggers before merge? If that can't be confirmed, one option is to ship the event without search_term, or behind a separate flag, until the privacy review is done. A light redaction step in searchTerm() (emails, long hex/base64-like runs, coder_-style token prefixes) would also lower the risk, whichever way the review goes.

@nickvigilante nickvigilante Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Partly addressed in 3a4f9d1. searchTerm() now replaces emails, coder_ tokens and runs of 32 or more token-like characters with [redacted] before the term is capped, and a test in both dialogs pins it. The README's description of search_term says so.

Not confirmed: whether GTM-NLLNT3K has a catch-all Custom Event trigger, or whether HockeyStack, Dreamdata, 6sense or Hotjar read dataLayer on their own. That needs someone with container access, and I can't check it from here. Redaction lowers the risk but doesn't remove it, so the README still says Security and Privacy should review search_term before it goes to Segment.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked against the production container. On coder.com/docs with marketing consent accepted, google_tag_manager["GTM-NLLNT3K"] was loaded. Nick pushed dataLayer.push({event: "docs_canary", search_term: "canary-9f3k2"}) and searched the Network tab in Chrome DevTools (Cmd+Option+F, which covers URLs, headers and response bodies). The string appeared in no request. So no catch-all Custom Event trigger fired on it, and no vendor script sent it on its own.

Two limits. This is the container as it is today, and Marketing can add a catch-all trigger later. Request payloads were not opened one by one, so a vendor that batches a POST body is not fully ruled out. Redaction is in 3a4f9d1, and the README still asks Security and Privacy to review search_term before it goes to Segment.

await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 25));
});
if (options().length > 0 && text === "install") break;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit type() polls for up to about 1 s, then always sleeps another 300 ms, and it only stops polling early when text === "install". That makes each test slow (the first test calls type three times, so each dialog spends about 4 s or more in that one test) and couples the helper to one fixture word. Waiting on the condition the test actually needs (for example data.query === text, through the status region or a settled options list) would be faster and less brittle. Mocked timers would also work.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3a4f9d1. type() now waits until the dialog's markup stops changing for 240 ms instead of sleeping a fixed 300 ms and stopping early only for "install". I couldn't wait on the status region as you suggested, because only the keyword dialog renders one. The suite went from about 25 s to 11 s, and the helper no longer depends on a fixture word.

…event tests

The search term reaches the data layer as soon as the container loads, so a catch-all trigger in the container would send it to vendors before the privacy review. Emails, coder_ tokens and long token-like runs are now replaced before the term is capped.

The test helper waited a fixed 300 ms and stopped early only for one fixture word. It now waits until the dialog markup settles, which works for both dialogs.

Assisted-by: AI
@vercel

vercel Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated
coder-docs Skipped Skipped Nov 30, 2026 10:29pm UTC

Request Review

@nickvigilante

Copy link
Copy Markdown
Collaborator Author

@Jesswinters re-requesting your review of 3a4f9d1 for one reason only: your P2 on search_term is a privacy question, so I'd like your eyes on the redaction and the canary result in the thread before this merges. The change from your approved commit is only your two review items: redaction in searchTerm() with a test in both dialogs, and the faster type() helper in the tests, plus the matching README line. Nothing else changed.

@Jesswinters Jesswinters left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for following up on both items. On the privacy question you asked me to look at:

  • The canary test against the production container is good evidence that no catch-all trigger exists today. You also stated its limits clearly: the container can change later, and batched POST bodies weren't opened.
  • The redaction runs before the 100-character cap, so a long token can't be cut down into a partial string that slips past the patterns.
  • I ran the patterns against sample strings, and they catch emails, Coder API keys (id-secret), GitHub PATs, UUIDs and JWT segments.
  • The README still asks for a Security/Privacy review before anything goes to Segment.

I'm comfortable merging on that basis. The faster type() helper also looks good, and the settle assertion fails loudly instead of passing early.

One non-blocking issue: the redaction now also catches some of the most common docs searches (1 P2, inline). That traces back to my coder_ suggestion, sorry. The fix is small.

Generated by Coder Agents on behalf of @Jesswinters.

Comment thread packages/docs-next/src/search-events.ts Outdated

const SECRET_PATTERNS: readonly RegExp[] = [
/[^\s@]+@[^\s@]+\.[^\s@]+/g,
/\bcoder_[\w-]+/gi,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 The coder_ pattern and the 32+ character pattern redact Terraform resource names and environment variable names, which are some of the main things people search the docs for.

I ran searchTerm() from this commit in Node:

coder_agent                          -> [redacted]
coder_parameter                      -> [redacted]
coder_workspace_preset               -> [redacted]
CODER_ACCESS_URL                     -> [redacted]   (the `i` flag)
CODER_OIDC_IGNORE_EMAIL_VERIFIED     -> [redacted]   (32+ chars of \w)
CODER_EXTERNAL_AUTH_0_CLIENT_SECRET  -> [redacted]

This isn't a privacy problem, but docs_search would tell Marketing nothing about the provider and config searches. That's a large share of the questions the event exists to answer, and it would happen without any visible sign. This one is on me: I suggested coder_ token prefixes, but Coder API keys use the id-secret form, which the long-run pattern already catches.

Suggested fix: drop the coder_ pattern, and let the long-run pattern skip snake_case identifiers made of short words:

const SECRET_PATTERNS: readonly RegExp[] = [
  /[^\s@]+@[^\s@]+\.[^\s@]+/g,
  // Long token-like runs, except snake_case identifiers of short words (CODER_*, coder_*).
  /(?<![\w+/=-])(?![A-Za-z][A-Za-z0-9]{0,15}(?:_[A-Za-z0-9]{1,16})+(?![\w+/=-]))[\w+/=-]{32,}/g,
];

With this version, all the identifiers above pass through unchanged. abcd123456-0123456789abcdefABCDEF (API key shape), ghp_<36 chars>, the JWT header and a1b2c3d4 repeated five times are still redacted. The test fixture would need coder_AbC123xyz taken out of the expected [redacted] set, and a case like coder_agent / CODER_ACCESS_URL passing through is worth adding. The tradeoff: a secret written as short underscore-joined words would survive, which seems acceptable.

Obs Hostnames and IPs aren't redacted (dial tcp coder.acme-internal.corp:443 comes through as is). The PR description lists hostnames as a concern. Redacting them would also remove searches like github.com, so leaving that to the Security/Privacy review the README asks for seems reasonable.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in the next commit on this branch. I ran your cases first: all six identifiers were redacted before, and pass through unchanged with your regex, while abcd123456-0123456789abcdefABCDEF, a ghp_ token, the JWT header, an sk_live_ key and a1b2c3d4 repeated five times are still redacted. I dropped the coder_ pattern, took your pattern as written, and updated the README line. The old test fixture is replaced by an API-key shape, and a new test in both dialogs checks that coder_workspace_preset, CODER_OIDC_IGNORE_EMAIL_VERIFIED and CODER_ACCESS_URL come through unchanged. Hostnames and IPs stay as they are, as you suggested, for the Security and Privacy review.

…search term

The coder_ pattern and the long-run pattern redacted names such as coder_agent and CODER_ACCESS_URL, which are among the most common docs searches, so the event told Marketing nothing about provider and config questions. Drop the coder_ pattern and let the long-run pattern skip snake_case names made of short words. API keys, GitHub tokens, JWT segments and long hex runs are still redacted.

Assisted-by: AI
The identifier exemption in the search term redaction only covers snake_case names of short words. Pin that a coder_<prefix>_<secret> value is still redacted, beside the API-key shape.

Assisted-by: AI

@ianjevans ianjevans left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@nickvigilante
nickvigilante merged commit b309228 into main Dec 3, 2026
37 of 40 checks passed
@nickvigilante
nickvigilante deleted the vigilante/docs-datalayer-events branch December 3, 2026 14:22

This branch is waiting to be deployed

1 inactive and 1 waiting deployments
docs-preview — 0e27cf28 Waiting Nov 30, 2026 by nickvigilante via preview / deploy preview #148
Preview — 0e27cf28 Deployed Nov 30, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants