Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support for Google Tag Manager environment config #2035

Open
wants to merge 8 commits into
base: develop
Choose a base branch
from

Conversation

tmchow
Copy link

@tmchow tmchow commented Feb 6, 2025

PR Description

Adds support for Google Tag Manager environment support which requires gtm_preview and gtm_auth params. This corresponds with the change in the rudder-integrations-config repo: rudderlabs/rudder-integrations-config#1894

Linear task (optional)

n/a

Cross Browser Tests

Please confirm you have tested for the following browsers:

  • Chrome
  • Firefox
  • IE11

Sanity Suite

  • All sanity suite test cases pass locally

Security

  • The code changed/added as part of this pull request won't create any security issues with how the software is being used.

Summary by CodeRabbit

  • New Features
    • Enhanced analytics integration by introducing validation checks for environment and authorization properties.
    • Improved resource loading through dynamic URL generation tailored to different deployment scenarios.

Corresponds to this change in the rudder-integrations-config repo:
rudderlabs/rudder-integrations-config#1894
@tmchow tmchow requested a review from a team as a code owner February 6, 2025 05:43
@tmchow tmchow requested review from utsabc and ItsSudip February 6, 2025 05:43
Copy link
Contributor

coderabbitai bot commented Feb 6, 2025

📝 Walkthrough

Walkthrough

The changes update the GoogleTagManager integration to support additional configuration parameters. In the browser.js file, two new properties, environmentID and authorizationToken, are added to the class constructor and validated. The init method is modified to pass these parameters during the SDK loading process. In the nativeSdkLoader.js file, the loadNativeSdk function is updated to accept these extra parameters and conditionally append them as query parameters in the script URL. The modifications enhance the configuration capabilities based on environment and authorization requirements.

Changes

File(s) Change Summary
packages/analytics-js-integrations/.../GoogleTagManager/browser.js Updated the GoogleTagManager constructor to include validation for environmentID and authorizationToken. Modified init() to pass these parameters when calling loadNativeSdk.
packages/analytics-js-integrations/.../GoogleTagManager/nativeSdkLoader.js Updated the loadNativeSdk function signature to accept environmentID and authorizationToken. Modified the script URL generation to conditionally append gtm_auth and gtm_preview query parameters based on passed values.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant GTM as GoogleTagManager
    participant Loader as NativeSdkLoader

    Client->>GTM: Instantiate with config (includes environmentID & authorizationToken)
    GTM->>GTM: Validate and extract new parameters from config
    GTM->>Loader: Call loadNativeSdk(containerID, serverUrl, environmentID, authorizationToken)
    Loader-->>GTM: Return loaded SDK
    GTM-->>Client: SDK initialized
Loading

Possibly related PRs

  • feat: snap extra parametrs pass #1921: The changes in the main PR are related to the modifications in the loadNativeSdk function, which now accepts environmentID and authorizationToken parameters, indicating a similar pattern of enhancing method signatures.

Suggested labels

DO NOT MERGE

Suggested reviewers

  • koladilip
  • ItsSudip
  • sandeepdsvs
  • shrouti1507

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 53093af and b048db9.

📒 Files selected for processing (1)
  • packages/analytics-js-integrations/src/integrations/GoogleTagManager/browser.js (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/analytics-js-integrations/src/integrations/GoogleTagManager/browser.js

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@tmchow tmchow changed the title feat: add gtm environment config feat(gtm): add gtm environment config Feb 6, 2025
@tmchow tmchow changed the title feat(gtm): add gtm environment config feat: add support for Google Tag Manager environment config Feb 6, 2025
Copy link
Contributor

@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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7952ad3 and f611aa3.

📒 Files selected for processing (2)
  • packages/analytics-js-integrations/src/integrations/GoogleTagManager/browser.js (2 hunks)
  • packages/analytics-js-integrations/src/integrations/GoogleTagManager/nativeSdkLoader.js (2 hunks)
🔇 Additional comments (3)
packages/analytics-js-integrations/src/integrations/GoogleTagManager/nativeSdkLoader.js (2)

3-3: LGTM! Function signature updated to support GTM environment configuration.

The new parameters align with GTM's requirements for environment-specific configuration.


19-19: Verify GTM URL format with official documentation.

The URL construction appears correct, but let's verify the format and required parameters against GTM's documentation.

✅ Verification successful

🌐 Web query:

What is the correct URL format for Google Tag Manager's gtm.js with environment and authorization parameters?

💡 Result:

The correct URL format for Google Tag Manager's `gtm.js` script with environment and authorization parameters combines your container ID with specific environment identifiers:

```
https://www.googletagmanager.com/gtm.js?id=GTM-XXXXXX&env=EnvironmentID&auth=AuthorizationCode
```

### Key components explained:
1. **Container ID** (`id=GTM-XXXXXX`):  
   Your unique GTM container identifier[4][7].

2. **Environment parameter** (`env=EnvironmentID`):  
   Specifies which pre-configured environment (e.g., development/staging/production) to load[5][9]. Environment IDs are found in GTM's Admin interface under Environments[5].

3. **Authorization code** (`auth=AuthorizationCode`):  
   A security token generated for each environment to control access[5][9]. This code appears in the environment configuration details[5].

### Example implementation:
```html
<script>
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id=GTM-ABCD1234&env=54&auth=zdk93k2Fd%3D';f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-ABCD1234');
</script>
```

### Important considerations:
- Use HTTPS protocol for security compliance[4][9]
- Environment IDs and auth codes are case-sensitive[5]
- Authorization codes expire when environments are modified - regenerate them after changes[5]
- Protocol-relative URLs (`//www.googletagmanager.com...`) remain supported for legacy implementations[4]

This structure allows controlled deployment of tags through different environments while maintaining security through authorization codes[5][9].

Citations:

- 1: https://measureschool.com/url-variable-gtm/
- 2: https://developers.google.com/tag-platform/tag-manager/api/v2/authorization
- 3: https://developers.google.com/tag-platform/tag-manager/api/v2/devguide
- 4: https://developers.google.com/tag-platform/tag-manager/protocol-relative-url
- 5: https://developers.google.com/tag-platform/tag-manager/api/v2/reference/accounts/containers/environments
- 6: https://support.google.com/tagmanager/answer/7683362
- 7: https://developers.google.com/tag-platform/tag-manager/datalayer
- 8: https://support.google.com/tagmanager/answer/6107163?hl=en
- 9: https://www.simoahava.com/analytics/google-tag-template-in-google-tag-manager/
- 10: https://www.simoahava.com/analytics/custom-templates-guide-for-google-tag-manager/

GTM URL structure is compliant with the official documentation.
The URL construction in the code correctly uses the container identifier (id), environment (env), and authorization (auth) parameters when combined with the additional parameters (such as the data layer and cookies).

  • Ensure that each variable (e.g., gtmAuth and gtmEnv) includes the respective parameter key (like &auth= and &env=) as prescribed by GTM's documentation.
  • Verify that window.finalUrl is set to "https://www.googletagmanager.com" to conform to the required HTTPS protocol.
packages/analytics-js-integrations/src/integrations/GoogleTagManager/browser.js (1)

30-30: LGTM! init() method correctly passes GTM environment configuration.

The initialization properly forwards the environment and authorization parameters to the native SDK loader.

tmchow and others added 2 commits February 5, 2025 21:51
…anager/nativeSdkLoader.js

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
…anager/browser.js

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Contributor

@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: 1

🧹 Nitpick comments (1)
packages/analytics-js-integrations/src/integrations/GoogleTagManager/browser.js (1)

19-27: Enhance validation to prevent invalid value assignment.

While the validation checks are good, the code still assigns potentially invalid values. Consider preventing the assignment of invalid values.

     // Validate environment configuration
     if (config.environmentID && typeof config.environmentID !== 'string') {
       logger.error('GTM environmentID must be a string');
+      return;
     }
     if (config.authorizationToken && typeof config.authorizationToken !== 'string') {
       logger.error('GTM authorizationToken must be a string');
+      return;
     }
     this.environmentID = config.environmentID;
     this.authorizationToken = config.authorizationToken;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f611aa3 and 53093af.

📒 Files selected for processing (2)
  • packages/analytics-js-integrations/src/integrations/GoogleTagManager/browser.js (2 hunks)
  • packages/analytics-js-integrations/src/integrations/GoogleTagManager/nativeSdkLoader.js (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/analytics-js-integrations/src/integrations/GoogleTagManager/nativeSdkLoader.js
🔇 Additional comments (2)
packages/analytics-js-integrations/src/integrations/GoogleTagManager/browser.js (2)

38-38: LGTM!

The init method correctly passes the GTM environment configuration parameters to the SDK loader.


1-109: Verify integration with rudder-integrations-config repository.

Since this PR corresponds to changes in rudder-integrations-config repository (PR #1894), let's verify the integration.

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Description: Check if the integration matches the config repository changes

# Clone and check the related PR in rudder-integrations-config
git clone https://github.com/rudderlabs/rudder-integrations-config.git
cd rudder-integrations-config
git fetch origin pull/1894/head:pr-1894
git checkout pr-1894

# Search for GTM environment configuration changes
echo "Checking GTM configuration changes in PR #1894:"
rg -A 5 "environmentID|authorizationToken" .

Length of output: 3119


GTM Configuration Integration Verified

The integration in the analytics-js-integrations repository correctly aligns with the changes in the rudder-integrations-config repository (PR #1894). The updated configuration files in the config repo now support environmentID and authorizationToken—matching the validations and parameters handled by the GoogleTagManager integration in this code.

…anager/browser.js

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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.

1 participant