Repository navigation
feat: making storeURL dynamic based on the current location - #3189
Conversation
|
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. |
WalkthroughReplaces static store URL usages with a runtime-resolved Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
Important Action Needed: IP Allowlist UpdateIf your organization protects your Git platform with IP whitelisting, please add the new CodeRabbit IP address to your allowlist:
Reviews will stop working after February 8, 2026 if the new IP is not added to your allowlist. 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 |
There was a problem hiding this comment.
Actionable comments posted: 7
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/core/src/sdk/analytics/platform/vtex/search.ts (1)
20-39: Consider lazy domain resolution for defensive SSR compatibility
createOrRefreshCookieevaluatesgetStoreURL()at module initialization (lines 23–28), which executes whensearch.tsis imported. AlthoughgetStoreURL()includes a server guard, deferring domain computation to the cookie write phase and wrapping in error handling would be more resilient.Suggested improvement
const createOrRefreshCookie = (key: string, expiresSecond: number) => { - const urlDomain = - process.env.NODE_ENV === 'development' - ? '.localhost' - : config.secureSubdomain - ? getBaseDomain([getStoreURL(), config.secureSubdomain]) - : `.${new URL(getStoreURL()).hostname}` - return () => { + const urlDomain = (() => { + if (process.env.NODE_ENV === 'development') return '.localhost' + try { + const storeURL = getStoreURL() + return config.secureSubdomain + ? getBaseDomain([storeURL, config.secureSubdomain]) + : `.${new URL(storeURL).hostname}` + } catch { + return '' + } + })() let currentValue = getCookie(key) const isExpired = currentValue === undefined if (isExpired) { currentValue = randomUUID() } - document.cookie = `${key}=${currentValue}; max-age=${expiresSecond}; domain=${urlDomain}; path=/;` + const domainAttr = urlDomain ? `; domain=${urlDomain}` : '' + document.cookie = `${key}=${currentValue}; max-age=${expiresSecond}${domainAttr}; path=/;`
🤖 Fix all issues with AI agents
In
`@packages/core/src/components/account/MyAccountDrawer/OrganizationDrawer/OrganizationDrawer.tsx`:
- Around line 118-120: The logout URL uses getStoreURL() directly which can
produce malformed URLs when the store URL contains paths or query params; update
the call in the window.location.assign invocation that builds
`${storeConfig.secureSubdomain}/api/vtexid/pub/logout?scope=${storeConfig.api.storeId}&returnUrl=${getStoreURL()}`
to encode the returnUrl with encodeURIComponent(getStoreURL()) and provide a
safe fallback (e.g., encodeURIComponent('/') or encodeURIComponent(getStoreURL()
|| '/')) so the constructed logout URL is always valid; change the string
interpolation in the window.location.assign call in OrganizationDrawer.tsx
accordingly (references: window.location.assign, storeConfig, getStoreURL).
In `@packages/core/src/components/templates/LandingPage/LandingPage.tsx`:
- Around line 66-89: The storeURL returned by getStoreURL() can end with a
trailing slash which causes double slashes in Canonical and search target
strings; normalize storeURL inside the LandingPage component (e.g., in the
variable storeURL) by trimming any trailing slash before using it in
NextSeo.canonical and SiteLinksSearchBoxJsonLd.target so concatenations like
`${storeURL}/${slug}` and `${storeURL}/s/?q` never produce `//`; update
references to storeURL used in openGraph.url and SiteLinksSearchBoxJsonLd.url as
well to use the normalized value.
In
`@packages/core/src/components/templates/ProductListingPage/ProductListingPage.tsx`:
- Around line 105-116: The canonical and breadcrumb URL construction currently
concatenates getStoreURL() with pathnames (used when building canonical and in
the itemListElements map), which can duplicate locale segments; replace string
concatenation with URL joining via the URL constructor (e.g., construct new
URL(pathname, storeURL).href) when building canonical and when computing pageUrl
inside the itemListElements map to normalize and avoid duplicated locale/path
segments; update uses of canonical and pageUrl to use the URL-based result.
In `@packages/core/src/pages/s.tsx`:
- Around line 90-92: The canonical construction using searchTerm is unsafe (it
only replaces spaces); update the logic that builds canonical in pages/s.tsx to
use the URL and URLSearchParams APIs to properly encode the query: create a new
URL(getStoreURL()), call url.searchParams.set('q', searchTerm) when searchTerm
is present, and set canonical = url.toString(); keep canonical undefined when
searchTerm is falsy and ensure you reference the existing getStoreURL and
searchTerm symbols and the canonical variable.
In `@packages/core/src/sdk/account/refreshToken.ts`:
- Around line 31-35: REFRESH_TOKEN_URL and the Host header currently build from
getStoreURL() directly which can include path segments or trailing slashes;
parse getStoreURL() once with the URL constructor (e.g., const u = new
URL(getStoreURL())) and use u.origin to construct REFRESH_TOKEN_URL
(`${u.origin}/api/vtexid/refreshtoken/webstore`) and u.host (or u.hostname with
port if needed) for the Host header passed through sanitizeHost, replacing the
existing uses of getStoreURL() in the REFRESH_TOKEN_URL and headers (refer to
the REFRESH_TOKEN_URL constant, headers object, sanitizeHost and getStoreURL).
In `@packages/core/src/sdk/localization/useLocalizationConfig.tsx`:
- Around line 28-33: The render currently calls setSettings directly (comparing
settings and newSettings), which violates React rules; instead, compute
newSettings by calling getSettings(params) but perform the deepEqual check and
call setSettings(newSettings) inside a useEffect hook (e.g., in
useLocalizationConfig's body) with appropriate dependencies (params or the
specific values used to derive newSettings) so updates happen after render; keep
the initial useState<Settings>(getSettings(params)) initializer, remove the
direct setSettings from the render, and reference getSettings, settings,
newSettings, and deepEqual when moving the logic into the effect.
In `@packages/core/test/sdk/localization/store-url.browser.test.ts`:
- Around line 92-95: The test restores window.location in an afterAll hook which
causes cross-test pollution; change the hook to afterEach so window.location is
reset after each individual test. Locate the existing afterAll block that
assigns window.location = oldWindowLocation and replace it with afterEach to
ensure each test that mutates window.location is cleaned up; keep the
oldWindowLocation variable reference and restore it inside the afterEach
callback exactly as was done in the afterAll.
🧹 Nitpick comments (7)
packages/core/src/pages/[slug]/p.tsx (1)
114-121: CachegetStoreURL()before mapping breadcrumbs.
Line 114-121:getStoreURL()is called per item; compute once for clarity and minor perf.Suggested fix
const description = meta?.description || pdpSeo.descriptionTemplate.replace(/%s/g, () => title) || storeSeo.description + + const storeURL = getStoreURL() let itemListElements = product.breadcrumbList.itemListElement ?? [] if (itemListElements.length !== 0) { itemListElements = itemListElements.map( ({ item: pathname, name, position }) => { - const pageUrl = getStoreURL() + pathname + const pageUrl = storeURL + pathname return { name, position, item: pageUrl } } ) }packages/core/test/sdk/localization/store-url.test.ts (1)
90-95: Consider expanding test coverage for edge cases.The test only verifies the default locale (pt-BR) returns its first binding. Consider adding tests for:
- When localization is disabled
- When binding lookup fails (fallback behavior)
- Non-default locale resolution
This would complement the browser tests that cover
window.locationscenarios.packages/core/src/sdk/offer/fetcher.ts (1)
7-14: Consider cachinggetStoreURL()result for performance.
getStoreURL()is called on everygetUrl(skuId)invocation. SincegetStoreURL()performs URL matching internally, repeated calls in hot paths (e.g., batch SKU lookups) could add overhead.If
getUrlis called frequently, consider caching the base URL:♻️ Optional performance optimization
const IS_PROD = process.env.NODE_ENV === 'production' +let cachedBaseUrl: string | null = null export function getUrl(skuId: string) { const base = IS_PROD - ? getStoreURL() + ? (cachedBaseUrl ??= getStoreURL()) : `https://${api.storeId}.${api.environment}.com.br` const url = new URL(`${base}/api/intelligent-search/product_search`)packages/core/test/sdk/localization/store-url.browser.test.ts (2)
104-119:delete window.locationmay not work reliably in strict mode.Using
delete window.locationcan fail silently in strict mode or newer JSDOM versions. Consider usingObject.definePropertyto override instead:♻️ More robust location mocking
it('should return the correct binding when window.location.href is defined', () => { - delete window.location - window.location = Object.defineProperties( - {}, + Object.defineProperty(window, 'location', { + configurable: true, + writable: true, + value: Object.defineProperties({}, { + ...Object.getOwnPropertyDescriptors(oldWindowLocation), + href: { + configurable: true, + value: config.localization.locales['en-US'].bindings[0].url, + }, + }), + }) - { - ...Object.getOwnPropertyDescriptors(oldWindowLocation), - href: { - configurable: true, - value: config.localization.locales['en-US'].bindings[0].url, - }, - } - )
4-86: Consider extracting shared mock configuration to reduce duplication.The mock configuration is nearly identical to
store-url.test.ts. Extract to a shared test fixture:// test/fixtures/localization-mock.ts export const mockLocalizationConfig = { enabled: true, defaultLocale: 'pt-BR', ... }packages/core/src/sdk/localization/useLocalizationConfig.tsx (2)
128-138: Avoidas unknown as Propstype assertion.The double cast through
unknownbypasses TypeScript's type checking. Consider a cleaner generic constraint:♻️ Improved type safety
export function withStoreURL< Props extends { storeURL: string }, - PartialProps extends Omit<Props, 'storeURL'> & { storeURL?: string }, ->(Component: React.ComponentType<Props>): React.ComponentType<PartialProps> { - return (props: PartialProps) => { - return React.createElement(Component, { +>(Component: React.ComponentType<Props>): React.ComponentType<Omit<Props, 'storeURL'> & { storeURL?: string }> { + const WrappedComponent = (props: Omit<Props, 'storeURL'> & { storeURL?: string }) => { + const resolvedProps = { ...props, storeURL: props.storeURL ?? getStoreURL(), - } as unknown as Props) + } as Props + return React.createElement(Component, resolvedProps) } + WrappedComponent.displayName = `withStoreURL(${Component.displayName || Component.name || 'Component'})` + return WrappedComponent }
109-115: Redundant config check - localization was already accessed.The check
if (!config.localization)on line 109 occurs afterconfig.localization.localeswas already accessed on lines 84-86. If localization were missing, this would have already thrown.♻️ Move check earlier or remove
function getSettings(params?: { url?: string | URL }) { let url = params?.url ?? '' + + if (!config.localization) { + throw new Error('Missing localization configuration in faststore config file.') + } + const defaultConfig = config.localization.locales[ config.localization.defaultLocale ] as ConfigType // ... rest of function - - if (!config.localization) { - const Err = new Error( - 'Missing localization configuration in faststore config file.' - ) - console.error(Err) - throw Err - }
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/core/package.json (1)
95-108:⚠️ Potential issue | 🟡 MinorTighten Node engine constraint for jsdom compatibility.
jsdom 27.4.0 requires Node >=20.19.0, but the package.json engines field allows
>=20, which includes Node 20.0–20.18. Updateengines.nodeto>=20.19.0to prevent install/runtime failures.@vitejs/plugin-react5.1.2 (Vite 7 compatible) and@testing-library/react14.3.1 (React 18 compatible) are aligned with the project's versions.
🧹 Nitpick comments (2)
packages/core/src/sdk/localization/useLocalizationConfig.tsx (2)
88-121: Move the localization guard before first access.The guard currently runs after dereferencing
config.localization, so missing config would throw earlier with a less actionable error.♻️ Proposed adjustment
function getSettings(params?: { url?: string | URL }) { + if (!config.localization) { + const Err = new Error( + 'Missing localization configuration in faststore config file.' + ) + console.error(Err) + throw Err + } let url = params?.url ?? '' const defaultConfig = config.localization.locales[ config.localization.defaultLocale ] as ConfigType @@ - if (!config.localization) { - const Err = new Error( - 'Missing localization configuration in faststore config file.' - ) - console.error(Err) - throw Err - }
3-3: Expose optional URL parameter togetStoreURLfor SSR/SEO correctness.
getSettingsalready supports a URL parameter to ensure correct locale binding in server contexts, butgetStoreURLdoesn't. Server-side callers will always resolve the default binding whenwindowis unavailable, which can leak the wrong locale host into canonical/SEO links. Expose an optional URL param matchinggetSettings' signature and ensure SSR callers pass it to build region-correct canonical links.🔧 Proposed signature update
-export const getStoreURL = () => getSettings().storeURL +export const getStoreURL = (params?: { url?: string | URL }) => + getSettings(params).storeURLReact namespace import on line 3 is justified by
withStoreURL'screateElementcall.
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/core/src/sdk/localization/useLocalizationConfig.tsx (1)
43-63:⚠️ Potential issue | 🟡 MinorPotential re-render loop:
sessionin useEffect dependencies.Including
sessionas a dependency while callingsessionStore.set()(which updates session state) inside the same effect can trigger unnecessary re-renders. Consider using a ref to track the previous session or restructuring to avoid this.🛡️ One possible approach using functional update pattern
useEffect(() => { if (!settings) return - const channel = JSON.parse(session.channel ?? '{}') ?? {} - channel.salesChannel = settings.salesChannel - - const newSession = { - ...session, - locale: settings.locale, - currency: settings.currency, - channel: JSON.stringify(channel), - } - - if ( - newSession.channel !== session.channel || - newSession.locale !== session.locale || - deepEqual(newSession.currency, session.currency) === false - ) { - sessionStore.set(newSession) - } - }, [settings, session]) + const currentSession = sessionStore.read() ?? sessionStore.readInitial() + const channel = JSON.parse(currentSession.channel ?? '{}') ?? {} + channel.salesChannel = settings.salesChannel + + const newSession = { + ...currentSession, + locale: settings.locale, + currency: settings.currency, + channel: JSON.stringify(channel), + } + + if ( + newSession.channel !== currentSession.channel || + newSession.locale !== currentSession.locale || + deepEqual(newSession.currency, currentSession.currency) === false + ) { + sessionStore.set(newSession) + } + }, [settings])
🧹 Nitpick comments (2)
packages/core/src/sdk/localization/useLocalizationConfig.tsx (2)
18-28: DRY violation:defaultConfiganddefaultBindingduplicated.This logic is repeated in both the hook body and in
getSettings()(lines 90-101). SincegetSettingsalready handles defaults, remove this duplication from the hook.♻️ Proposed refactor
export const useLocalizationConfig = (params?: { url?: string | URL }) => { const [session, setSession] = useState( sessionStore.read() ?? sessionStore.readInitial() ) - const defaultConfig = config.localization.locales[ - config.localization.defaultLocale - ] as ConfigType - const defaultBinding = - defaultConfig.bindings.find((el) => el.isDefault) ?? - defaultConfig.bindings.at(0) - - if (!defaultBinding) - throw new Error( - 'Localization configuration invalid: not found default binding' - ) - const [settings, setSettings] = useState<Settings>(() => getSettings(params))
133-144: AdddisplayNameto the HOC for better debugging.Without a
displayName, the wrapped component appears as "Anonymous" in React DevTools, making debugging harder.♻️ Proposed improvement
export function withStoreURL< Props extends { storeURL: string }, PartialProps extends Omit<Props, 'storeURL'> & { storeURL?: string }, >(Component: React.ComponentType<Props>): React.ComponentType<PartialProps> { - return (props: PartialProps) => { + const WrappedComponent = (props: PartialProps) => { return React.createElement(Component, { ...props, storeURL: props.storeURL ?? getStoreURL(), } as unknown as Props) } + WrappedComponent.displayName = `withStoreURL(${Component.displayName ?? Component.name ?? 'Component'})` + return WrappedComponent }
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/core/src/sdk/localization/useLocalizationConfig.tsx (1)
43-63:⚠️ Potential issue | 🟡 MinorConsider preventing unnecessary effect re-runs when sessionStore updates via subscription.
The effect depends on both
settingsandsessionbut callssessionStore.set, which may trigger the subscription callback (lines 37-41) that callssetSession. This causes the effect to run again when the subscription updatessessionstate. While thedeepEqualcheck insessionStore.setprevents infinite loops, the effect body still executes unnecessarily. To optimize, track whether the session was just updated from the store callback or memoize the comparison logic to avoid the second execution.
🧹 Nitpick comments (3)
packages/core/src/sdk/localization/useLocalizationConfig.tsx (3)
18-28: Duplicated defaultConfig/defaultBinding logic.Lines 18-28 duplicate the same logic found in
getSettings()at lines 90-101. Extract this to a shared helper to reduce maintenance burden and ensure consistency.♻️ Proposed refactor
+function getDefaultConfigAndBinding() { + const defaultConfig = config.localization.locales[ + config.localization.defaultLocale + ] as ConfigType + const defaultBinding = + defaultConfig.bindings.find((el) => el.isDefault) ?? + defaultConfig.bindings.at(0) + + if (!defaultBinding) { + throw new Error( + 'Localization configuration invalid: not found default binding' + ) + } + return { defaultConfig, defaultBinding } +}Then use
getDefaultConfigAndBinding()in bothuseLocalizationConfigandgetSettings.
131-138: Confusing boolean expression.
!config.localization?.enabled === trueis hard to parse due to operator precedence. Simplify for readability.✨ Suggested improvement
export const getStoreURL = () => { // If localization is not enabled, use storeUrl from config - if (!config.localization?.enabled === true) { + if (!config.localization?.enabled) { return config.storeUrl } return getSettings().storeURL }
140-151: HOC implementation looks correct but consider adding displayName for debugging.The
withStoreURLHOC correctly injectsstoreURLas an optional prop. Adding adisplayNameimproves React DevTools debugging.✨ Suggested improvement
export function withStoreURL< Props extends { storeURL: string }, PartialProps extends Omit<Props, 'storeURL'> & { storeURL?: string }, >(Component: React.ComponentType<Props>): React.ComponentType<PartialProps> { - return (props: PartialProps) => { + const WrappedComponent = (props: PartialProps) => { return React.createElement(Component, { ...props, storeURL: props.storeURL ?? getStoreURL(), } as unknown as Props) } + WrappedComponent.displayName = `withStoreURL(${Component.displayName || Component.name || 'Component'})` + return WrappedComponent }
## What's the purpose of this pull request? Removing hardcoded labels: - #3099 - #3102 - #3107 - #3104 - #3103 - #3125 - #3131 - #3116 - #3142 - #3192 Setting Up locales - #3141 - #3143 - #3147 - #3156 - #3162 - #3145 - #3164 - #3169 - #3171 - #3176 - #3180 - #3169 custom path - #3185 - #3162 - #3156 - #3170 Components - #3093 - #3175 Fetching content - #3165 Others - #3176 - #3171 - #3181 - #3189 - #3205 ## How to test locally? - Run `pnpm I` (install all the new dependencies and needed packages) - If you want to try localization feature, go to`/discovery.config.default.js`: Enable localization: ``` localization: { enabled: true } ``` - Run `node packages/cli/bin/run.js generate-i18n ./packages/core` to fetch the bindings If the contentSource is not set to content platform yet, you will see a message to update to it. > contentSource: { > type: 'CP', > },⚠️ Note: Ensure the url is set to localhost for local testing. These locale bindings are generated in `discovery.config` after running the generate-i18n command. ```diff localization: { enabled: true, defaultLocale: 'en-US', regions: {...}, locales: { 'pt-BR': { ... bindings: [ { currencyCode: 'BRL', - url: 'https://brandless.fast.store/pt-BR', + url: 'http://localhost:3000/pt-BR', salesChannel: '2', isDefault: true, locales: [ { code: 'pt-BR', isDefault: true, }, ], }, ], }, 'it-IT': { ... bindings: [ { currencyCode: 'EUR', - url: 'https://brandless.fast.store/it-IT', + url: 'http://localhost:3000/it-IT', salesChannel: '3', isDefault: true, locales: [ { code: 'it-IT', isDefault: true, }, ], }, { currencyCode: 'EUR', - url: 'https://brandless.fast.store/europe/it', + url: 'http://localhost:3000/europe/it', salesChannel: '3', isDefault: false, locales: [ { code: 'it-IT', isDefault: true, }, ], }, ], }, 'en-US': { code: 'en-US', name: 'English', languageCode: 'en', languageName: 'English', script: 'Latn', textDirection: 'ltr', regionCode: 'US', bindings: [ { currencyCode: 'USD', - url: 'https://brandless.fast.store', + url: 'http://localhost:3000, salesChannel: '1', isDefault: true, locales: [ { code: 'en-US', isDefault: true, }, ], }, ], }, ... } ``` - Go to /packages/core and run `npmn dev` --------- Co-authored-by: Larícia Mota <[email protected]> Co-authored-by: Leandro Rodrigues <[email protected]> Co-authored-by: Otavio Moreira Meirelles <[email protected]> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Addded two test case, one that simulates the running scenarioon on build time (node env) and other simulating browser with different locations to check wether the storeURL is returning the correct one.
Summary by CodeRabbit
New Features
Refactor
Tests
Chores