Repository navigation
fix: scripts improvements - update RC url + Partytown loading + logs + fix bugs. - #3198
Conversation
WalkthroughAdds 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
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
|
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. |
- 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.
There was a problem hiding this comment.
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_viewevents only whenrouter.asPathchanges, preventing duplicates even ifpropschanges on the same page. This is by design (as noted in the commit "improve props handling and page view event tracking")—page_viewis 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, andincludeVTEXcomputations are duplicated inThirdPartyScripts.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
|
@mariana-caetano we need to document the flag |
| const THIRTY_MINUTES_S = 30 * 60 | ||
| const ONE_YEAR_S = 365 * 24 * 3600 | ||
|
|
||
| const enableScriptsLogs = config.experimental?.enableScriptsLogs === true |
There was a problem hiding this comment.
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" |
There was a problem hiding this comment.
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.
What's the purpose of this pull request?
This PR:
Summary by CodeRabbit