Repository navigation
fix: subdomain locale/salesChannel loss while navigating - #3239
Conversation
WalkthroughSubdomain-aware locale bindings, validation, and channel resolution were added to localization utilities and wired into the proxy, link/session utilities, and page generation. getStaticProps now includes a channel derived from locale; proxy rewrites subdomain requests before standard rules; tests updated for new helpers. Changes
Sequence DiagramsequenceDiagram
participant Client
participant Proxy
participant Localization as LocalizationConfig
participant PageGen as PageGeneration
participant Response
Client->>Proxy: HTTP request (Host: fr.example.com)
Proxy->>Localization: getSubdomainBindings()
Localization-->>Proxy: [{ hostname: "fr.example.com", locale: "fr-FR" }]
Proxy->>Proxy: isValidLocale("fr-FR")
Proxy->>Proxy: rewriteSubdomainRequest() -> rewrite path/locale headers
Proxy->>PageGen: Rewritten request (locale header/param)
PageGen->>Localization: getChannelForLocale("fr-FR")
Localization-->>PageGen: "channel-fr"
PageGen->>PageGen: getStaticProps(locator: [slug, "channel-fr"])
PageGen-->>Response: Rendered HTML
Response-->>Client: HTML response
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
📝 Coding Plan
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. |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
packages/core/src/sdk/ui/useLink.ts (1)
44-44: Consider addingrouter.defaultLocaleto the dependency array.The callback reads
router.defaultLocalebut it's not listed in the deps. WhiledefaultLocaleis stable per domain and won't change during navigation (so this works correctly in practice), ESLint'sexhaustive-depsrule would flag this.If you intentionally omit it to avoid re-renders, a brief comment would clarify the intent. Otherwise, adding it is low-risk since it's stable:
♻️ Optional: include defaultLocale in deps
- [router.asPath, router.locale] + [router.asPath, router.locale, router.defaultLocale]🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/sdk/ui/useLink.ts` at line 44, The dependency array for the callback in useLink (currently [router.asPath, router.locale]) omits router.defaultLocale which is read inside the callback; update the deps to include router.defaultLocale to satisfy exhaustive-deps (i.e., change the array to include router.defaultLocale) or, if omission was intentional to avoid re-renders, add a concise comment next to the dependency array explaining that router.defaultLocale is stable and intentionally omitted for performance to satisfy reviewers and ESLint.packages/core/src/utils/localization/bindingPaths.ts (1)
288-312: Consider creating a fresh channel object instead of mutating the parsed default.While currently safe because
JSON.parsecreates a new object each call, directly mutatingchannelObjafter parsingdefaultChannelis fragile if the implementation ever changes to cache the parsed object.♻️ Slightly cleaner approach
const channelObj = JSON.parse(defaultChannel) - channelObj.salesChannel = binding.salesChannel + const updatedChannel = { ...channelObj, salesChannel: binding.salesChannel } - return filterChannel(JSON.stringify(channelObj)) + return filterChannel(JSON.stringify(updatedChannel))🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/utils/localization/bindingPaths.ts` around lines 288 - 312, In getChannelForLocale, avoid mutating the parsed defaultChannel; instead parse defaultChannel into a base (e.g., const baseChannel = JSON.parse(defaultChannel)) and create a fresh object for return (e.g., const newChannelObj = { ...baseChannel, salesChannel: binding.salesChannel }) so you do not modify the parsed object in-place; then return filterChannel(JSON.stringify(newChannelObj)). Keep references to storeConfig, localeConfig, binding and filterChannel unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/core/src/utils/utilities.ts`:
- Around line 120-123: The filterChannel function currently calls
JSON.parse(channel) which will throw on invalid or empty JSON (callers may pass
channel ?? ''), so wrap the parse in a validation and try/catch: if channel is
falsy or not valid JSON, return an appropriate empty JSON string (e.g., '{}' or
'[]' consistent with callers) instead of throwing; otherwise parse, perform the
existing destructuring (const { hasOnlyDefaultSalesChannel, ...filteredChannel }
= parsed), and return JSON.stringify(filteredChannel). Update the function name
filterChannel to handle non-string inputs robustly and include the try/catch
around JSON.parse to avoid runtime crashes.
---
Nitpick comments:
In `@packages/core/src/sdk/ui/useLink.ts`:
- Line 44: The dependency array for the callback in useLink (currently
[router.asPath, router.locale]) omits router.defaultLocale which is read inside
the callback; update the deps to include router.defaultLocale to satisfy
exhaustive-deps (i.e., change the array to include router.defaultLocale) or, if
omission was intentional to avoid re-renders, add a concise comment next to the
dependency array explaining that router.defaultLocale is stable and
intentionally omitted for performance to satisfy reviewers and ESLint.
In `@packages/core/src/utils/localization/bindingPaths.ts`:
- Around line 288-312: In getChannelForLocale, avoid mutating the parsed
defaultChannel; instead parse defaultChannel into a base (e.g., const
baseChannel = JSON.parse(defaultChannel)) and create a fresh object for return
(e.g., const newChannelObj = { ...baseChannel, salesChannel:
binding.salesChannel }) so you do not modify the parsed object in-place; then
return filterChannel(JSON.stringify(newChannelObj)). Keep references to
storeConfig, localeConfig, binding and filterChannel unchanged.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 84c0ab15-cedf-421f-991c-db9bb3b94476
📒 Files selected for processing (8)
packages/core/src/pages/[slug]/p.tsxpackages/core/src/proxy.tspackages/core/src/sdk/localization/match-url.tspackages/core/src/sdk/session/index.tspackages/core/src/sdk/ui/useLink.tspackages/core/src/utils/localization/bindingPaths.tspackages/core/src/utils/utilities.tspackages/core/test/utils/localization/bindingPaths.test.ts
| export function filterChannel(channel: string): string { | ||
| const { hasOnlyDefaultSalesChannel, ...filteredChannel } = JSON.parse(channel) | ||
| return JSON.stringify(filteredChannel) | ||
| } |
There was a problem hiding this comment.
Add error handling for invalid JSON input.
JSON.parse('') throws a SyntaxError. Since callers may pass channel ?? '' (e.g., session/index.ts line 193), this can crash at runtime.
🛡️ Proposed defensive fix
export function filterChannel(channel: string): string {
+ if (!channel) {
+ return '{}'
+ }
+ try {
const { hasOnlyDefaultSalesChannel, ...filteredChannel } = JSON.parse(channel)
return JSON.stringify(filteredChannel)
+ } catch {
+ console.warn('[filterChannel] Invalid channel JSON:', channel)
+ return channel
+ }
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export function filterChannel(channel: string): string { | |
| const { hasOnlyDefaultSalesChannel, ...filteredChannel } = JSON.parse(channel) | |
| return JSON.stringify(filteredChannel) | |
| } | |
| export function filterChannel(channel: string): string { | |
| if (!channel) { | |
| return '{}' | |
| } | |
| try { | |
| const { hasOnlyDefaultSalesChannel, ...filteredChannel } = JSON.parse(channel) | |
| return JSON.stringify(filteredChannel) | |
| } catch { | |
| console.warn('[filterChannel] Invalid channel JSON:', channel) | |
| return channel | |
| } | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/core/src/utils/utilities.ts` around lines 120 - 123, The
filterChannel function currently calls JSON.parse(channel) which will throw on
invalid or empty JSON (callers may pass channel ?? ''), so wrap the parse in a
validation and try/catch: if channel is falsy or not valid JSON, return an
appropriate empty JSON string (e.g., '{}' or '[]' consistent with callers)
instead of throwing; otherwise parse, perform the existing destructuring (const
{ hasOnlyDefaultSalesChannel, ...filteredChannel } = parsed), and return
JSON.stringify(filteredChannel). Update the function name filterChannel to
handle non-string inputs robustly and include the try/catch around JSON.parse to
avoid runtime crashes.
There was a problem hiding this comment.
The empty-string case is already handled: in JavaScript, '' is falsy, so if (!channel) is true when channel is ''. Callers that pass channel ?? '' (e.g. in session/index.ts) never reach JSON.parse when the value is an empty string — the function returns '{}' first. Invalid or malformed JSON is still caught by the existing try/catch, which logs a warning and returns the original value. No change needed for this comment.
There was a problem hiding this comment.
@lemagnetic, you're right — I missed that the full file content already includes both guards. The if (!channel) early return correctly handles empty/falsy strings before JSON.parse is ever called, and the try/catch covers malformed JSON. My concern doesn't apply here. Thanks for the clarification!
🧠 Learnings used
Learnt from: lemagnetic
Repo: vtex/faststore PR: 3236
File: packages/core/src/pages/[slug]/p.tsx:329-329
Timestamp: 2026-03-05T17:43:56.925Z
Learning: In `packages/core/src/pages/[slug]/p.tsx` (FastStore), PDP data is built from two queries merged with `deepmerge(server, client, { arrayMerge: overwriteMerge })` (~L157):
1. **Server**: `ServerProductQuery` — supplies server-only fields such as `breadcrumbList`.
2. **Client**: `ClientProductQuery` (via `useProductQuery`) — supplies locale-sensitive fields (title, description, SEO, offers) using the session locale; it does NOT include `breadcrumbList`.
Because `breadcrumbList` is never included in the client query, it is never overwritten by the merge and always reflects the server response. Removing `locale` from the `ServerProductQuery` locator only affects server-only fields (notably `breadcrumbList`) and does NOT de-localize the PDP content the user sees, which is driven entirely by the client query with session locale.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
packages/core/src/utils/localization/bindingPaths.ts (2)
21-21: Consider exposing a cache reset for test isolation.The module-level cache persists across test runs. Per the test file context, there are no
beforeEach/afterEachhooks resetting this cache, which could cause test order dependencies or flaky results if different test suites mock different configs.🧪 Suggested test utility
let bindingsByTypeCache: BindingsByType | null = null +/** `@internal` Exposed only for test cleanup */ +export function __resetBindingsCacheForTesting(): void { + bindingsByTypeCache = null +}Then in tests:
beforeEach(() => { __resetBindingsCacheForTesting() })🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/utils/localization/bindingPaths.ts` at line 21, The module-level cache bindingsByTypeCache causes test cross-talk; add and export a test-only reset function (e.g. __resetBindingsCacheForTesting) that sets bindingsByTypeCache = null, and export it from the same module so tests can call it in beforeEach/afterEach to isolate state; keep the function name clearly marked as testing-only (double-underscore) to avoid accidental production use.
141-151: Consider returning readonly arrays to prevent accidental cache mutation.Both functions return direct references to the cached arrays. If any consumer inadvertently mutates the returned array, it corrupts the cache for subsequent calls.
Options:
- Return
as const/ReadonlyArraytype to signal intent- Return shallow copy:
return [...getBindingsByType().customPaths]Not critical if consumers are well-behaved, but the readonly type at least catches accidental mutations at compile time.
🔧 Suggested type-safe approach
-export function getCustomPathsFromBindings(): CustomPathInfo[] { +export function getCustomPathsFromBindings(): readonly CustomPathInfo[] { return getBindingsByType().customPaths } -export function getSubdomainBindings(): SubdomainBinding[] { +export function getSubdomainBindings(): readonly SubdomainBinding[] { return getBindingsByType().subdomainBindings }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/utils/localization/bindingPaths.ts` around lines 141 - 151, Both getCustomPathsFromBindings and getSubdomainBindings currently return direct references to the cached arrays from getBindingsByType(), allowing callers to mutate the cache; change their signatures to return ReadonlyArray (e.g. ReadonlyArray<CustomPathInfo> and ReadonlyArray<SubdomainBinding>) and return a shallow copy of the arrays (e.g. spread into a new array) instead of the raw references from getBindingsByType(), so the cache cannot be accidentally mutated while still preserving runtime behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/core/src/utils/localization/bindingPaths.ts`:
- Around line 308-311: The JSON.parse(defaultChannel) call in bindingPaths.ts
can throw on malformed storeConfig.session.channel; wrap the parse in a
try-catch around the code that builds channelObj/updatedChannel (the
JSON.parse(defaultChannel) and subsequent updatedChannel = { ...channelObj,
salesChannel: binding.salesChannel }), and on error log the exception (using the
project logger or console.error) and return a safe fallback by calling
filterChannel on a known-good default (or an empty channel JSON) instead of
letting the exception bubble.
---
Nitpick comments:
In `@packages/core/src/utils/localization/bindingPaths.ts`:
- Line 21: The module-level cache bindingsByTypeCache causes test cross-talk;
add and export a test-only reset function (e.g. __resetBindingsCacheForTesting)
that sets bindingsByTypeCache = null, and export it from the same module so
tests can call it in beforeEach/afterEach to isolate state; keep the function
name clearly marked as testing-only (double-underscore) to avoid accidental
production use.
- Around line 141-151: Both getCustomPathsFromBindings and getSubdomainBindings
currently return direct references to the cached arrays from
getBindingsByType(), allowing callers to mutate the cache; change their
signatures to return ReadonlyArray (e.g. ReadonlyArray<CustomPathInfo> and
ReadonlyArray<SubdomainBinding>) and return a shallow copy of the arrays (e.g.
spread into a new array) instead of the raw references from getBindingsByType(),
so the cache cannot be accidentally mutated while still preserving runtime
behavior.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 20342631-4cd9-4b27-b94e-619686e18d90
📒 Files selected for processing (2)
packages/core/src/utils/localization/bindingPaths.tspackages/core/src/utils/utilities.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/core/src/utils/utilities.ts
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/core/src/utils/localization/bindingPaths.ts (1)
141-150: Expose defensive copies from binding getters to prevent accidental mutations.
getCustomPathsFromBindings()(line 142) andgetSubdomainBindings()(line 150) return direct references to cached arrays. While current callers only read these arrays, returning shared mutable references risks silent corruption if future code mutates them downstream.♻️ Proposed hardening
-type BindingsByType = { - customPaths: CustomPathInfo[] - subdomainBindings: SubdomainBinding[] -} +type BindingsByType = { + customPaths: ReadonlyArray<CustomPathInfo> + subdomainBindings: ReadonlyArray<SubdomainBinding> +} @@ export function getCustomPathsFromBindings(): CustomPathInfo[] { - return getBindingsByType().customPaths + return [...getBindingsByType().customPaths] } @@ export function getSubdomainBindings(): SubdomainBinding[] { - return getBindingsByType().subdomainBindings + return [...getBindingsByType().subdomainBindings] }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/utils/localization/bindingPaths.ts` around lines 141 - 150, getCustomPathsFromBindings() and getSubdomainBindings() currently return direct references to cached arrays from getBindingsByType(), which risks accidental external mutation; change both to return defensive copies (e.g., shallow copies) of getBindingsByType().customPaths and getBindingsByType().subdomainBindings so callers receive immutable copies. Update the implementations of getCustomPathsFromBindings and getSubdomainBindings to clone the arrays before returning (use Array.prototype.slice or spread) and keep the rest of the behavior unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/core/src/utils/localization/bindingPaths.ts`:
- Around line 141-150: getCustomPathsFromBindings() and getSubdomainBindings()
currently return direct references to cached arrays from getBindingsByType(),
which risks accidental external mutation; change both to return defensive copies
(e.g., shallow copies) of getBindingsByType().customPaths and
getBindingsByType().subdomainBindings so callers receive immutable copies.
Update the implementations of getCustomPathsFromBindings and
getSubdomainBindings to clone the arrays before returning (use
Array.prototype.slice or spread) and keep the rest of the behavior unchanged.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 68882ee7-901e-4e81-a869-291f1b8eb7ff
📒 Files selected for processing (1)
packages/core/src/utils/localization/bindingPaths.ts
What's the purpose of this pull request?
When using subdomain bindings for localization (e.g.,
https://fr.brandless.fast.store→fr-FR), the locale is correctly identified on the initial page load but gets lost during client-side navigation (search, PDP links, etc.), falling back to the default locale (en-US). This causes two issues:matchURLBindingdoesn't recognize subdomain-only bindings (root pathname/) as a match for non-root paths.getStaticPropsqueries the GraphQL API using the default sales channel instead of the locale-specific one, so products exclusive to a subdomain's catalog are not found.How it works?
Subdomain binding recognition in
match-url.ts: Added logic so that when a binding URL has a root pathname (/), it's treated as a subdomain binding — the hostname alone determines the locale. This prevents the locale from being lost when navigating to paths like/s(search) or/product/p.Middleware rewriting in
proxy.ts:rewriteSubdomainRequestfunction that internally rewrites requests to prepend the correct locale for subdomain domains. This ensuresgetStaticPropsreceives the rightlocaleparameter without exposing it in the browser URL./_next/data/:path*requests (client-side data fetches), so locale corrections also apply during client-side navigation.getChannelForLocale(locale)utility that resolves the correct sales channel for a given locale by looking up its binding configuration.getStaticPropsnow passes the resolved channel in thelocatorarray, ensuring the GraphQL product query uses the locale-specific sales channel instead of always defaulting to the channel present in discovery.config (session.channel).useLink.ts: Changed the default locale reference fromstoreConfig.localization.defaultLocaletorouter.defaultLocale. On subdomain domains, Next.js setsrouter.defaultLocaleto the domain's locale (e.g.,fr-FR), so using the global config default would incorrectly prepend locale prefixes to every link.How to test it?
discovery.config.default.js(e.g.,https://fr.brandless.fast.storeforfr-FRwith sales channel3)http://fr.brandless.fast.store:3000)fr-FRon the initial page loadfr-FR/fr-FR/product/p)Untitled.mov
Starters Deploy Preview
References
Summary by CodeRabbit
Improvements
Tests