Repository navigation
fix: localization race condition - #3281
Conversation
WalkthroughThis PR extracts localization settings into a central module, updates the hook to use it, boots the session with a URL-aware initial session, and installs a one-shot corrector that reconciles stale persisted session locale/currency/channel during hydration. ChangesLocalization Settings Extraction & Session Initialization
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. |
6c7ef8e to
4d4ac3a
Compare
61c02a2 to
79fea9b
Compare
@faststore/api
@faststore/cli
@faststore/components
@faststore/core
@faststore/diagnostics
@faststore/lighthouse
@faststore/sdk
@faststore/ui
commit: |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
packages/core/test/sdk/session/installLocaleCorrector.browser.test.ts (1)
22-22: ⚡ Quick winUse deterministic microtask flushing instead of fixed sleeps
await sleep(50)makes these tests time-based and can be flaky in CI. Since this path is microtask-driven, use a flush helper (await Promise.resolve()chain) for deterministic assertions.Proposed refactor
-const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) +const flushMicrotasks = async () => { + await Promise.resolve() + await Promise.resolve() +} @@ - await sleep(50) + await flushMicrotasks() @@ - await sleep(50) + await flushMicrotasks() @@ - await sleep(50) + await flushMicrotasks() @@ - await sleep(50) + await flushMicrotasks() @@ - await sleep(50) + await flushMicrotasks() @@ - await sleep(50) + await flushMicrotasks() @@ - await sleep(50) + await flushMicrotasks()Also applies to: 68-68, 95-95, 117-117, 131-131, 144-144, 150-150, 164-164
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/core/test/sdk/session/installLocaleCorrector.browser.test.ts` at line 22, The tests use a time-based helper sleep (const sleep) and await sleep(50) which makes assertions flaky; replace this with a deterministic microtask flush helper (e.g., a function named flushMicrotasks that returns a Promise resolved via queueMicrotask or a chained Promise.resolve) and then swap every await sleep(50) occurrence in the test file (references: the sleep helper and test calls at the various locations) to await flushMicrotasks() so assertions run after microtasks complete instead of waiting a fixed timeout.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/core/src/sdk/localization/settings.ts`:
- Around line 35-37: The code dereferences config.localization when computing
defaultConfig (variable defaultConfig and references to
config.localization.locales and config.localization.defaultLocale) before the
existing guard that checks for a missing localization config; move the guard
that validates config.localization (the explicit error branch currently at lines
~59-65) to run before any access to config.localization, or defer computing
defaultConfig until after that guard (or use safe checks/optional chaining) so
the intended error message is thrown instead of a generic runtime error.
In `@packages/core/src/sdk/session/initialSession.ts`:
- Around line 83-86: The JSON.parse calls in initialSession.ts (parsing
session.channel and initialSession.channel) can throw on malformed IDB data;
wrap each parse in a safe parse fallback (try/catch or a small safeParse helper)
so that channel defaults to {} on failure and the salesChannel assignment uses
the safely parsed object (i.e., protect parsing of session.channel and
initialSession.channel before using channel.salesChannel). Ensure you reference
and update the variables channel, session.channel, initialSession.channel and
salesChannel so the one-shot locale correction never throws on bad JSON.
---
Nitpick comments:
In `@packages/core/test/sdk/session/installLocaleCorrector.browser.test.ts`:
- Line 22: The tests use a time-based helper sleep (const sleep) and await
sleep(50) which makes assertions flaky; replace this with a deterministic
microtask flush helper (e.g., a function named flushMicrotasks that returns a
Promise resolved via queueMicrotask or a chained Promise.resolve) and then swap
every await sleep(50) occurrence in the test file (references: the sleep helper
and test calls at the various locations) to await flushMicrotasks() so
assertions run after microtasks complete instead of waiting a fixed timeout.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: ceb0b5ab-b228-443d-973c-62bf3070a597
📒 Files selected for processing (6)
packages/core/src/sdk/localization/settings.tspackages/core/src/sdk/localization/useLocalizationConfig.tsxpackages/core/src/sdk/session/index.tspackages/core/src/sdk/session/initialSession.tspackages/core/test/sdk/session/getInitialSession.browser.test.tspackages/core/test/sdk/session/installLocaleCorrector.browser.test.ts
|
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/core/src/sdk/session/initialSession.ts`:
- Around line 11-20: safeParseChannel currently treats JSON arrays as valid
objects which causes installs like installLocaleCorrector to mutate an array and
lose properties when re-serialized; update safeParseChannel to parse the value
the same way but explicitly reject arrays (use Array.isArray(parsed) check) and
return {} for arrays or non-object results so only plain objects are accepted;
reference function safeParseChannel (and where installLocaleCorrector reads
session.channel) to locate and change the logic.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: ce9750b0-8a1e-4707-8bad-0eb4b65724f7
📒 Files selected for processing (3)
packages/core/src/sdk/localization/settings.tspackages/core/src/sdk/session/initialSession.tspackages/core/test/sdk/session/installLocaleCorrector.browser.test.ts
| function safeParseChannel( | ||
| value: string | null | undefined | ||
| ): Record<string, unknown> { | ||
| if (!value) return {} | ||
| try { | ||
| const parsed = JSON.parse(value) | ||
| return parsed && typeof parsed === 'object' ? parsed : {} | ||
| } catch { | ||
| return {} | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
In JavaScript, if const arr = JSON.parse('[]'); arr.salesChannel = '1';, does JSON.stringify(arr)includesalesChannel?
💡 Result:
Yes. In const arr = JSON.parse('[]'); arr.salesChannel = '1';, salesChannel will be included by JSON.stringify(arr) (assuming it’s an enumerable own property, as regular assignment creates it). JSON.stringify() “includes only enumerable own properties” when no replacer filters are provided, and it ignores non-enumerable properties. [1][2] So with your example, salesChannel is an enumerable own string-keyed property on the array object, meaning it will be visited and serialized into the resulting JSON string (e.g., it will appear as a property of the array’s serialized object). [1][2] Note: if you added it as non-enumerable, it would be omitted; symbol-keyed properties are also ignored. [1][3]
Citations:
- 1: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
- 2: https://www.blackdogcat.xyz/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
- 3: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol
🏁 Script executed:
#!/bin/bash
node - <<'NODE'
const arr = JSON.parse('[]')
arr.salesChannel = '1'
console.log('stringify:', JSON.stringify(arr))
console.log('keys:', Object.keys(arr))
console.log('hasOwnProperty salesChannel:', Object.prototype.hasOwnProperty.call(arr,'salesChannel'))
NODERepository: vtex/faststore
Length of output: 131
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="packages/core/src/sdk/session/initialSession.ts"
nl -ba "$FILE" | sed -n '1,180p'Repository: vtex/faststore
Length of output: 101
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="packages/core/src/sdk/session/initialSession.ts"
cat -n "$FILE" | sed -n '1,220p'Repository: vtex/faststore
Length of output: 4482
Reject array-shaped channel in safeParseChannel
safeParseChannel currently treats arrays as valid objects; if persisted session.channel is '[]', installLocaleCorrector assigns salesChannel onto the array but JSON.stringify(array) outputs only [], so the corrected salesChannel is lost.
Suggested fix
function safeParseChannel(
value: string | null | undefined
): Record<string, unknown> {
if (!value) return {}
try {
const parsed = JSON.parse(value)
- return parsed && typeof parsed === 'object' ? parsed : {}
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
+ ? parsed
+ : {}
} catch {
return {}
}
}📝 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.
| function safeParseChannel( | |
| value: string | null | undefined | |
| ): Record<string, unknown> { | |
| if (!value) return {} | |
| try { | |
| const parsed = JSON.parse(value) | |
| return parsed && typeof parsed === 'object' ? parsed : {} | |
| } catch { | |
| return {} | |
| } | |
| function safeParseChannel( | |
| value: string | null | undefined | |
| ): Record<string, unknown> { | |
| if (!value) return {} | |
| try { | |
| const parsed = JSON.parse(value) | |
| return parsed && typeof parsed === 'object' && !Array.isArray(parsed) | |
| ? parsed | |
| : {} | |
| } catch { | |
| return {} | |
| } | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/core/src/sdk/session/initialSession.ts` around lines 11 - 20,
safeParseChannel currently treats JSON arrays as valid objects which causes
installs like installLocaleCorrector to mutate an array and lose properties when
re-serialized; update safeParseChannel to parse the value the same way but
explicitly reject arrays (use Array.isArray(parsed) check) and return {} for
arrays or non-object results so only plain objects are accepted; reference
function safeParseChannel (and where installLocaleCorrector reads
session.channel) to locate and change the logic.

0 New Issues
0 Fixed Issues
4 Accepted Issues
What's the purpose of this pull request?
Fixes the multi-language race condition where the
LocalizationSelectorwould briefly flicker (or stay stuck on the wrong value) right after page load, because IDB-hydrated sessions could overwrite the URL-derived locale before the session reached a stable state.This was previously mitigated by a workaround in the V4 Canary (#3111) that rewrote
session.locale/currency/channelinsidevalidateSessionbefore sending the mutation. That kept the backend in sync but still allowed a visible flicker, since the local store transiently held the stale value. This PR removes the workaround and addresses the root cause.How it works?
Two coordinated changes inside
packages/core/src/sdk/session/:getInitialSession()seedsdefaultStorewith the URL-derivedlocale/currency/salesChannelat module load (instead of the default values fromdiscovery.config.session). First-visit and SSR are unaffected.installLocaleCorrector()registers a one-shot subscriber AFTER theoptimisticmiddleware. When the persisted middleware later hydrates from IDB with a stale locale, the corrector re-entersstore.set(corrected)synchronously. The base store'scancelations.forEach(cancel)flips thecancelflag on the just-enqueuedvalidateSession(stale)handler — so it bails before reaching the network — and a fresh handler is enqueued with the corrected locale. The result: exactly onevalidateSessioncall, with the right locale, and no flicker inuseSession().Both helpers were extracted to
packages/core/src/sdk/session/initialSession.tsto keep them framework-free and unit-testable.The workaround block inside
validateSession(PR #3111) is no longer needed and was removed.How to test it?
faststore-core-i18n-setupskill or by settinglocalization.enabled = trueindiscovery.config.jswith at least two locale bindings)./en-US/) in a fresh browser tab or after clearing IDB (fs::session).ValidateSession. Expected: a single mutation with the URL-aligned locale. Before the fix, two were issued (one with the default/stale locale, one with the URL locale).LocalizationSelectorin the header — it should render the correct locale immediately, with no transient flicker.Automated coverage:
cd packages/core pnpm vitest run test/sdk/session/getInitialSession.browser.test.ts pnpm vitest run test/sdk/session/installLocaleCorrector.browser.test.tsgetInitialSession.browser.test.ts(6 tests) — URL-aware seeding, channel merge, fallback paths.installLocaleCorrector.browser.test.ts(6 tests) — the cancellation property, one-shot behavior, unsubscribe.Summary by CodeRabbit
New Features
Bug Fixes
Tests
tested in https://brandless.fast.store/
References
Task https://vtex-dev.atlassian.net/jira/software/c/projects/SFS/boards/1051?selectedIssue=SFS-3145