Skip to content

fix: scripts improvements - update RC url + Partytown loading + logs + fix bugs. - #3198

Merged
eduardoformiga merged 5 commits into
devfrom
chore/updates-rc-script-SFS-3027
Feb 10, 2026
Merged

eduardoformiga merged 5 commits into
devfrom
chore/updates-rc-script-SFS-3027

Conversation

@eduardoformiga

@eduardoformiga eduardoformiga commented Feb 3, 2026 •

Copy link
Copy Markdown
Member

What's the purpose of this pull request?

This PR:

  • Update the RC script URL to the new one as suggested.
  • Fix bugs related to Partytown load.
  • Fix bugs related to script events: RC pageview event duplicated or not triggering.
  • Adds Logs to improve observability of Partytown, Search Events, GTM, RC, AF, etc under an experimental flag.
Screenshot 2026-02-05 at 12 47 18

Summary by CodeRabbit

  • New Features
    • Optional runtime debug logging for third‑party analytics/scripts (toggleable via config).
  • Improvements
    • Google Tag Manager improved integration with Partytown for deferred/routed execution and conditional debug behavior.
    • Page view reporting debounced to avoid duplicate events on the same path.
    • Analytics payloads standardized for search/platform events.
  • Bug Fixes
    • Updated VTEX integration endpoint to the latest service URL.

@eduardoformiga
eduardoformiga requested a review from a team as a code owner February 3, 2026 19:40
@eduardoformiga
eduardoformiga requested review from lemagnetic and ommeirelles and removed request for a team February 3, 2026 19:40
@coderabbitai

coderabbitai Bot commented Feb 3, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds configurable runtime logging for GTM and VTEX scripts, introduces LOG_LABEL_STYLE and experimental.enableScriptsLogs, updates VTEX RC host to io2.vtex.com, injects Partytown configuration in _document, deduplicates page_view events, and simplifies Layout children props handling.

Changes

Cohort / File(s) Summary
Third-Party scripts — VTEX & GTM
packages/core/src/components/ThirdPartyScripts/vtex.tsx, packages/core/src/components/ThirdPartyScripts/GoogleTagManager.tsx, packages/core/src/components/ThirdPartyScripts/ThirdPartyScripts.tsx
Add enableScriptsLogs flag usage and LOG_LABEL_STYLE; conditionally wrap GTM dataLayer.push and VTEX RC/AF event calls with console.debug when enabled; update VTEX RC URL host to https://io2.vtex.com/rc/rc.js; remove Partytown import/forwards from ThirdPartyScripts.
Runtime HTML / Partytown
packages/core/src/pages/_document.tsx
Inject inline Partytown configuration and loader scripts; compute forwards and enable debug/logCalls based on GTM, VTEX, and enableScriptsLogs.
Configuration & constants
packages/core/discovery.config.default.js, packages/core/src/constants.ts
Add experimental.enableScriptsLogs default flag and export LOG_LABEL_STYLE constant.
Analytics & SDK
packages/core/src/sdk/analytics/platform/vtex/search.ts, packages/core/src/sdk/analytics/hooks/usePageViewEvent.ts
search.ts: build structured payload, send via fetch body, and emit optional debug logs when enabled. usePageViewEvent: useRef to deduplicate page_view by comparing router.asPath.
Layout
packages/core/src/Layout.tsx
Remove previous useMemo approach for children props; use isValidElement check and extract props at render time (typing/memoization simplified).

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Browser
    participant Server as FastStore Server rgba(241,196,15,0.5)
    participant Partytown as Partytown (web worker) rgba(52,152,219,0.5)
    participant GTM as GoogleTagManager rgba(46,204,113,0.5)
    participant VTEX as VTEX RC/AF rgba(155,89,182,0.5)

    User->>Browser: request page
    Browser->>Server: fetch HTML (_document injects Partytown config & scripts)
    Server-->>Browser: HTML with Partytown config and inline loaders
    Browser->>Partytown: initialize (if enabled)
    Browser->>VTEX: load VTEX RC/AF script (from io2.vtex.com)
    Browser->>GTM: initialize dataLayer and GTM script
    alt enableScriptsLogs = true
      Browser->>Browser: wrap dataLayer.push and VTEX event calls with console.debug
    end
    User->>Browser: interactions
    Browser->>Partytown: forward events (if configured)
    Partytown->>GTM: forward dataLayer pushes (if forwarded)
    GTM->>Server: network calls / tracking as configured
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • lemagnetic
  • hellofanny

Poem

🛠️ Scripts now whisper, logs in bloom,
Partytown hums from its worker-room,
VTEX points to io2's shore,
DataLayer sings and debugs roar,
Events sit tidy, paths repeat no more.

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title references multiple key changes (RC URL update, Partytown loading, logs, bug fixes) but lacks specificity about the primary change and uses vague language like 'improvements' and 'bugs'. Clarify the primary objective—either lead with the most critical fix (e.g., 'RC URL update') or rename to something more specific like 'fix: RC script migration and Partytown debugging enhancements' to better convey the scope.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chore/updates-rc-script-SFS-3027

No actionable comments were generated in the recent review. 🎉


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@codesandbox-ci

codesandbox-ci Bot commented Feb 3, 2026 •

Copy link
Copy Markdown

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

@lemagnetic lemagnetic left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

lgtm

- Introduced a new configuration option `enableScriptsLogs` to control logging of script events.
- Updated Google Tag Manager and VTEX components to log relevant events to the console when logging is enabled.
- Added a new constant `LOG_LABEL_STYLE` for consistent log styling across the application.
…n configuration

- Removed unnecessary imports and simplified the ThirdPartyScripts component.
- Moved Partytown configuration to the _document.tsx file for better management.
- Added dynamic handling of the GTM debug query string to improve GTM event visibility during development.
- Ensured Partytown script is only loaded when not in an iframe to prevent cross-origin issues.
- Updated the `Layout` component to handle undefined children more gracefully by adjusting the `useMemo` dependency.
- Enhanced the `usePageViewEvent` hook to prevent redundant page view events by tracking the last visited path with a ref, ensuring events are only sent on actual path changes.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@packages/core/src/Layout.tsx`:
- Around line 6-9: The current useMemo of children in useMemo(() => (children as
ReactElement | undefined)?.props, [children]) is ineffective because children
gets a new reference each render; instead, either move the memoization to the
parent so a stable prop object is passed into Layout, or compute and memoize
only the specific, stable values needed by usePageViewEvent (e.g., route,
pathname, or a specific child prop) and use those as the dependency keys; also
replace the unsafe type assertion with a runtime guard using
React.isValidElement(children) before reading children.props (e.g., const
childProp = React.isValidElement(children) ? children.props.someStableKey :
undefined) and memoize childProp (not children) to pass into usePageViewEvent.
🧹 Nitpick comments (3)
packages/core/src/components/ThirdPartyScripts/GoogleTagManager.tsx (1)

15-26: Complex inline script is hard to maintain—consider extracting to a template.

The string concatenation with conditional logging wrapper is difficult to read and debug. Consider extracting the script generation into separate helper functions or using template literals more cleanly.

♻️ Suggested refactor for readability
const getLoggingWrapper = (dataLayer: string) => enableScriptsLogs
  ? `w[l].push=(function(orig){return function(){console.debug("%cvtex%c GTM dataLayer.push","${LOG_LABEL_STYLE}","color:inherit",arguments);return orig.apply(this,arguments);}})(w[l].push);`
  : '';

const useSnippet = (opts: Props & { partytownScript: boolean }) => {
  const dataLayer = opts.dataLayerName ?? 'dataLayer'
  const prefix = opts.partytownScript ? '!' : ''
  const loggingWrapper = getLoggingWrapper(dataLayer)
  
  return `${prefix}window.location.search.includes('${GTM_DEBUG_QUERY_STRING}=')&&
  (function(w,d,s,l,i){w[l]=w[l]||[];
  ${loggingWrapper}
  w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});
  // ... rest of script
  })(window,document,'script',${JSON.stringify(dataLayer)},${JSON.stringify(opts.containerId)});`
}
packages/core/src/sdk/analytics/hooks/usePageViewEvent.ts (1)

24-29: Path-based page view deduplication is intentional; clarify design if needed.

The hook fires page_view events only when router.asPath changes, preventing duplicates even if props changes on the same page. This is by design (as noted in the commit "improve props handling and page view event tracking")—page_view is semantically tied to navigation, not component updates. Props are still included in the event params when fired.

If this navigation-only behavior should be explicit, add a comment explaining the design.

packages/core/src/pages/_document.tsx (1)

9-14: Consider extracting shared config logic.

The gtmContainerId, includeGTM, and includeVTEX computations are duplicated in ThirdPartyScripts.tsx. Consider extracting these to a shared utility for consistency.

♻️ Example extraction
// packages/core/src/utils/analytics-config.ts
import storeConfig from 'discovery.config'

export const gtmContainerId = storeConfig.analytics?.gtmContainerId
export const includeGTM = typeof gtmContainerId === 'string'
export const includeVTEX = storeConfig.platform === 'vtex'
export const enableScriptsLogs = storeConfig.experimental?.enableScriptsLogs === true

Comment thread packages/core/src/Layout.tsx Resolved
@eduardoformiga eduardoformiga changed the title fix: update VTEX script source URL to new domain fix: scripts improvements Feb 5, 2026
@eduardoformiga eduardoformiga changed the title fix: scripts improvements fix: scripts improvements - update RC url + Partytown loading + logs + fix bugs. Feb 5, 2026
@eduardoformiga

Copy link
Copy Markdown
Member Author

@mariana-caetano we need to document the flag enableScriptsLogs.

const THIRTY_MINUTES_S = 30 * 60
const ONE_YEAR_S = 365 * 24 * 3600

const enableScriptsLogs = config.experimental?.enableScriptsLogs === true

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Maybe creating a way do enable this feature without needing a rebuild would be nice.

type="text/partytown"
async
src="https://io.vtex.com.br/rc/rc.js"
src="https://io2.vtex.com/rc/rc.js"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

just checking: any breaking changes here? Should merchants expect anything different on their end, or are we just finally catching up on some tech debt? 😬

- Replaced useMemo with isValidElement to streamline the props extraction from children, improving readability and performance.
- Ensured that undefined children are handled gracefully in the usePageViewEvent hook.
@eduardoformiga
eduardoformiga merged commit 9a35b63 into dev Feb 10, 2026
3 checks passed
@eduardoformiga
eduardoformiga deleted the chore/updates-rc-script-SFS-3027 branch February 10, 2026 13:23
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.

4 participants