Skip to content

Fides.gcm - Define gtag as a fallback when its not already defined#7543

Open
jjdaurora wants to merge 16 commits intomainfrom
jjdaurora/ENG-2849
Open

Fides.gcm - Define gtag as a fallback when its not already defined#7543
jjdaurora wants to merge 16 commits intomainfrom
jjdaurora/ENG-2849

Conversation

@jjdaurora
Copy link
Contributor

@jjdaurora jjdaurora commented Mar 2, 2026

Ticket ENG-2849

Description Of Changes

  • This PR augments the existing Fides.gcm method that integrates with Google Consent Mode
  • Defines gtag when it is not defined, instead of logging a warning and returning early.
  • This change will make implementations simpler and removes the dependency of having gtag load prior to the method call.

Code Changes

 const dataLayer = window.dataLayer = window.dataLayer || [];

    function gtag(){
      dataLayer.push(arguments);
    }

Steps to Confirm

!-- list any manual steps for reviewers to confirm the changes -->

  • From fides, load fides-js-demo.html where gtag currently doesn't load
  • Add Fides.gcm to the page
  • Observe that the GTAG Consent Update in the dataLayer queue

Pre-Merge Checklist

  • Issue requirements met
  • All CI pipelines succeeded
  • CHANGELOG.md updated
    • Add a db-migration This indicates that a change includes a database migration label to the entry if your change includes a DB migration
    • Add a high-risk This issue suggests changes that have a high-probability of breaking existing code label to the entry if your change includes a high-risk change (i.e. potential for performance impact or unexpected regression) that should be flagged
    • Updates unreleased work already in Changelog, no new entry necessary
  • UX feedback:
    • All UX related changes have been reviewed by a designer
    • No UX review needed
  • Followup issues:
    • Followup issues created
    • No followup issues
  • Database migrations:
    • Ensure that your downrev is up to date with the latest revision on main
    • Ensure that your downgrade() migration is correct and works
      • If a downgrade migration is not possible for this change, please call this out in the PR description!
    • No migrations
  • Documentation:
    • Documentation complete, PR opened in fidesdocs
    • Documentation issue created in fidesdocs
    • If there are any new client scopes created as part of the pull request, remember to update public-facing documentation that references our scope registry
    • No documentation updates required

Summary by CodeRabbit

  • Improvements
    • Added a dataLayer-backed fallback so consent pushes continue working when the primary analytics function is unavailable.
    • Updated diagnostic messaging to indicate when the fallback is active and added a global declaration so dataLayer is recognized.

@jjdaurora jjdaurora requested a review from a team as a code owner March 2, 2026 23:21
@jjdaurora jjdaurora requested review from speaker-ender and removed request for a team March 2, 2026 23:21
@vercel
Copy link
Contributor

vercel bot commented Mar 2, 2026

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

2 Skipped Deployments
Project Deployment Actions Updated (UTC)
fides-plus-nightly Ignored Ignored Preview Mar 6, 2026 10:03pm
fides-privacy-center Ignored Ignored Mar 6, 2026 10:03pm

Request Review

@jjdaurora jjdaurora requested review from thabofletcher and tvandort and removed request for speaker-ender March 2, 2026 23:21
@jjdaurora jjdaurora changed the title gcm.ts; define gtag when its not undefined; Fides.gcm - Define gtag as a fallback when its not already defined Mar 2, 2026
@greptile-apps
Copy link
Contributor

greptile-apps bot commented Mar 2, 2026

Greptile Summary

This PR modifies gcm.ts to define a local gtag stub (backed by window.dataLayer) when window.gtag is not already present, rather than logging a warning and returning early. This follows the standard Google-recommended pattern for environments where gtag.js hasn't loaded yet, and correctly allows consent commands to be queued in dataLayer for Google to process once it does load.

  • The overall approach is sound and matches the established gtm.ts pattern of initializing window.dataLayer defensively.
  • A commented-out fidesDebugger call is left in the code as dead code rather than being removed or replaced with an active log message.
  • The function gtag() declaration uses the legacy arguments object instead of TypeScript rest parameters, which deviates from the project's TypeScript conventions. If the arguments object must be pushed exactly as-is (the official Google stub pattern), this deviation should be documented with an eslint-disable comment.

Confidence Score: 4/5

  • This PR is safe to merge with minor cleanup — the functional logic is correct and follows established patterns in the codebase.
  • The core change is a small, well-understood pattern (defining a dataLayer-backed gtag stub) that matches how gtm.ts already handles window.dataLayer. The only concerns are code quality: commented-out dead code and non-idiomatic use of arguments. No logic bugs or security issues were found.
  • No files require special attention beyond the minor style issues in clients/fides-js/src/integrations/gcm.ts.

Important Files Changed

Filename Overview
clients/fides-js/src/integrations/gcm.ts Changes the behavior when window.gtag is not found: instead of logging a warning and returning, it now defines a local dataLayer-backed stub. The functional approach is correct and follows the standard Google gtag.js stub pattern. Minor style issues include commented-out dead code and use of the legacy arguments object instead of TypeScript rest parameters.

Last reviewed commit: 8a08744

Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

1 file reviewed, 2 comments

Edit Code Review Agent Settings | Greptile

@coderabbitai
Copy link

coderabbitai bot commented Mar 4, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds an ambient window.dataLayer?: any[] declaration and changes pushConsentToGtag to initialize window.dataLayer and install a dataLayer-backed fallback window.gtag (pushing args to dataLayer and logging a fallback) instead of returning early when window.gtag is not a function.

Changes

Cohort / File(s) Summary
Google Consent Mode Integration
clients/fides-js/src/integrations/gcm.ts
Added ambient dataLayer?: any[] to Window. Modified pushConsentToGtag to initialize window.dataLayer, define a fallback window.gtag that pushes to dataLayer, and change the diagnostic to indicate the fallback; removed the previous early-return path.
Changelog
CHANGELOG.md
Added an "Added" entry noting the dataLayer / gtag stubbing logic in the Fides.gcm integration.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐇 I nibbled a hole where a gtag might hide,

Tucked a soft dataLayer so pushes can glide,
When gtag skips town, I hop in its stead,
Pushing consent crumbs where trackers are led,
A carrot-sweet fallback to keep things in stride.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: adding a fallback gtag function when it's not already defined in Fides.gcm.
Description check ✅ Passed The description includes the ticket number, clear explanation of changes, code changes, steps to confirm, and completed pre-merge checklist with appropriate selections.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch jjdaurora/ENG-2849

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
clients/fides-js/src/integrations/gcm.ts (1)

158-178: setGoogleConsentDefaults is currently unused.

This helper is defined but never invoked in this file. Please either wire it into the initialization flow or remove it to avoid dead code drift.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@clients/fides-js/src/integrations/gcm.ts` around lines 158 - 178, The helper
setGoogleConsentDefaults is defined but never used; either wire it into the GCM
initialization flow (call setGoogleConsentDefaults(consent, mapping) from the
module's initialization function such as initializeGcm / configureGcm where
consent/mapping are available so default consent is pushed to gtag/dataLayer),
or remove the function and its export entirely to avoid dead code—ensure you
also update any related tests and exports if you choose removal.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@clients/fides-js/src/integrations/gcm.ts`:
- Around line 163-169: The guard verifies window.gtag is not a function but then
uses nullish coalescing which can leave a non-function value in place; change
both gtag fallback blocks so they unconditionally assign a proper fallback: set
window.dataLayer to a fallback array via assignment (e.g. window.dataLayer =
window.dataLayer || []) and assign window.gtag to the fallback function directly
(e.g. window.gtag = function gtag(){ dataLayer.push(arguments) }) instead of
using ??, and apply the same change in the second fallback block that references
window.gtag/window.dataLayer.
- Line 165: Add the missing dataLayer property to the global Window augmentation
so TypeScript knows about window.dataLayer; update the existing declare global {
interface Window { gtag?: GtagFunction; dataLayer?: any[]; } } declaration in
this file (the same augmentation that currently declares gtag) so references to
window.dataLayer in the gcm integration (accesses at window.dataLayer =
window.dataLayer ?? [] and the later usage) no longer produce type errors.

---

Nitpick comments:
In `@clients/fides-js/src/integrations/gcm.ts`:
- Around line 158-178: The helper setGoogleConsentDefaults is defined but never
used; either wire it into the GCM initialization flow (call
setGoogleConsentDefaults(consent, mapping) from the module's initialization
function such as initializeGcm / configureGcm where consent/mapping are
available so default consent is pushed to gtag/dataLayer), or remove the
function and its export entirely to avoid dead code—ensure you also update any
related tests and exports if you choose removal.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b6cd571e-5281-4f62-b9fc-a4cf40bf64d4

📥 Commits

Reviewing files that changed from the base of the PR and between 0e58255 and 1eed1e2.

📒 Files selected for processing (1)
  • clients/fides-js/src/integrations/gcm.ts

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
clients/fides-js/src/integrations/gcm.ts (1)

154-175: ⚠️ Potential issue | 🟠 Major

Fix CI-blocking lint errors in the fallback block.

Line 171 currently fails ESLint (prefer-destructuring), and this block also triggers the reported formatting/lint warnings. Please adjust this section so frontend checks pass.

Suggested patch
-/**
- *
- * Push consent to Google Consent Mode v2
- */
+/**
+ * Push consent to Google Consent Mode v2
+ */
 const pushConsentToGtag = (
   consent: NoticeConsent,
   options: GcmOptions,
 ): void => {
@@
   if (typeof window.gtag !== "function") {
     // define dataLayer if it doesn't exist yet so that we can push to it in the gtag function fallback
     window.dataLayer ??= [];
-    const dataLayer = window.dataLayer;
+    const { dataLayer } = window;
     // define gtag if it doesn't exist and push to dataLayer
-    window.gtag = function gtag(){
-      dataLayer.push(arguments)
-    }
+    window.gtag = function gtag(...args: unknown[]) {
+      dataLayer!.push(args);
+    };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@clients/fides-js/src/integrations/gcm.ts` around lines 154 - 175, The
fallback block in pushConsentToGtag triggers ESLint prefer-destructuring and
formatting errors; change window.dataLayer ??= []; followed by const dataLayer =
window.dataLayer; to use destructuring: window.dataLayer ??= []; const {
dataLayer } = window; and reformat the gtag fallback to a properly spaced and
terminated function (e.g., function gtag() { dataLayer.push(arguments); }) so
linting/formatting rules pass while preserving behavior of pushConsentToGtag and
the window.gtag fallback.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@clients/fides-js/src/integrations/gcm.ts`:
- Around line 154-175: The fallback block in pushConsentToGtag triggers ESLint
prefer-destructuring and formatting errors; change window.dataLayer ??= [];
followed by const dataLayer = window.dataLayer; to use destructuring:
window.dataLayer ??= []; const { dataLayer } = window; and reformat the gtag
fallback to a properly spaced and terminated function (e.g., function gtag() {
dataLayer.push(arguments); }) so linting/formatting rules pass while preserving
behavior of pushConsentToGtag and the window.gtag fallback.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a4d8a7bc-f2be-4eab-ad29-dd4cac3231f2

📥 Commits

Reviewing files that changed from the base of the PR and between 3cb5a11 and 40e0d02.

📒 Files selected for processing (1)
  • clients/fides-js/src/integrations/gcm.ts

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.

2 participants