Skip to content

fix: localization race condition - #3281

Merged
lemagnetic merged 4 commits into
devfrom
chore/fix-localization-race-condition
May 28, 2026
Merged

lemagnetic merged 4 commits into
devfrom
chore/fix-localization-race-condition

Conversation

@gabpaladino

@gabpaladino gabpaladino commented Apr 16, 2026 •

Copy link
Copy Markdown
Member

What's the purpose of this pull request?

Fixes the multi-language race condition where the LocalizationSelector would 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/channel inside validateSession before 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/:

  1. getInitialSession() seeds defaultStore with the URL-derived locale / currency / salesChannel at module load (instead of the default values from discovery.config.session). First-visit and SSR are unaffected.

  2. installLocaleCorrector() registers a one-shot subscriber AFTER the optimistic middleware. When the persisted middleware later hydrates from IDB with a stale locale, the corrector re-enters store.set(corrected) synchronously. The base store's cancelations.forEach(cancel) flips the cancel flag on the just-enqueued validateSession(stale) handler — so it bails before reaching the network — and a fresh handler is enqueued with the corrected locale. The result: exactly one validateSession call, with the right locale, and no flicker in useSession().

Both helpers were extracted to packages/core/src/sdk/session/initialSession.ts to 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?

  1. Enable localization in a starter / local environment (e.g. via the faststore-core-i18n-setup skill or by setting localization.enabled = true in discovery.config.js with at least two locale bindings).
  2. Open the storefront on a non-default binding (e.g. /en-US/) in a fresh browser tab or after clearing IDB (fs::session).
  3. Open DevTools → Network and filter by 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).
  4. Watch the LocalizationSelector in the header — it should render the correct locale immediately, with no transient flicker.
  5. Switch locales via the selector and confirm the value stays consistent after navigation, and that hard-reload on the new binding doesn't trigger the issue again.

Automated coverage:

cd packages/core
pnpm vitest run test/sdk/session/getInitialSession.browser.test.ts
pnpm vitest run test/sdk/session/installLocaleCorrector.browser.test.ts
  • getInitialSession.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

    • Improved automatic locale and currency detection from the current URL for more accurate regional content and pricing.
    • Session initialization now respects URL-derived localization so users see correct locale, currency, and sales channel on load.
  • Bug Fixes

    • Prevents stale persisted sessions from overriding URL-aware localization; corrections apply once and preserve other session data.
  • Tests

    • Added browser-focused tests covering initialization, hydration correction, and edge cases (malformed session data).

Review Change Stack

tested in https://brandless.fast.store/

References
Task https://vtex-dev.atlassian.net/jira/software/c/projects/SFS/boards/1051?selectedIssue=SFS-3145

@coderabbitai

coderabbitai Bot commented Apr 16, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

This 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.

Changes

Localization Settings Extraction & Session Initialization

Layer / File(s) Summary
Settings module extraction
packages/core/src/sdk/localization/settings.ts
New module exports LocalizationSettings type and two helpers: getSettingsFromConfig derives locale, currency symbol, and salesChannel from a binding; getSettings resolves settings by matching the current URL against configured locale bindings or falling back to default.
useLocalizationConfig refactor
packages/core/src/sdk/localization/useLocalizationConfig.tsx
Removes the file-local getSettings implementation and local Settings type; imports and uses the centralized LocalizationSettings and getSettings, preserving public helpers like getStoreURL and withStoreURL.
Session imports and bootstrap
packages/core/src/sdk/session/index.ts
Removes inline localization sync and uses createSessionStore(getInitialSession(), onValidate); conditionally installs installLocaleCorrector when localization is enabled in the browser.
Initial session & corrector implementation
packages/core/src/sdk/session/initialSession.ts
Adds safeParseChannel, getInitialSession(defaults?) to seed URL-aware locale/currency/salesChannel into the initial session, and installLocaleCorrector(store, initialSession) as a one-time subscriber to correct stale persisted hydration by rewriting channel.salesChannel.
getInitialSession tests
packages/core/test/sdk/session/getInitialSession.browser.test.ts
Browser Vitest suite validating URL-driven seeding, salesChannel updates within channel JSON, preservation of other defaults, fallback to configured default binding, and non-destructive behavior when defaults already match the URL.
installLocaleCorrector tests
packages/core/test/sdk/session/installLocaleCorrector.browser.test.ts
Comprehensive browser tests covering microtask-cancellation timing, single corrected validation, preservation of non-locale payload fields, channel JSON rewriting, idempotent/one-shot behavior, unsubscribe semantics, and malformed channel resilience.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • vtex/faststore#3279: Related changes to packages/core/src/sdk/session/index.ts that update session locale/currency/channel handling from URL-derived settings.
  • vtex/faststore#3296: Related session/localization gating changes affecting when localization recalculation runs.
  • vtex/faststore#3256: Related modifications to useLocalizationConfig and URL-binding handling used by this PR.

Suggested labels

bug

Suggested reviewers

  • eduardoformiga
  • ommeirelles
  • lemagnetic

Poem

🧭 Settings pulled into a single chest,
URL whispers which locale is best,
Hydration wakes — a one-shot mend,
Sales channel set, old ghosts end. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 57.14% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: fixing a localization race condition where IDB-hydrated sessions could overwrite URL-derived locales, causing flickering in the UI.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
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
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chore/fix-localization-race-condition

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

@codesandbox-ci

codesandbox-ci Bot commented Apr 16, 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.

Base automatically changed from canary-v2 to dev May 6, 2026 20:30
@eduardoformiga
eduardoformiga force-pushed the dev branch 2 times, most recently from 6c7ef8e to 4d4ac3a Compare May 7, 2026 15:18
@lemagnetic
lemagnetic force-pushed the chore/fix-localization-race-condition branch from 61c02a2 to 79fea9b Compare May 25, 2026 01:20
@pkg-pr-new

pkg-pr-new Bot commented May 25, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@faststore/api

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/cli

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/components

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/core

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/diagnostics

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/lighthouse

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/sdk

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/ui

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

commit: ac542d2

@lemagnetic lemagnetic changed the title Try fix localization race condition fix: localization race condition May 25, 2026
@lemagnetic
lemagnetic marked this pull request as ready for review May 25, 2026 21:09
@lemagnetic
lemagnetic requested a review from a team as a code owner May 25, 2026 21:09
@lemagnetic
lemagnetic requested review from eduardoformiga and renatomaurovtex and removed request for a team May 25, 2026 21:09

@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: 2

🧹 Nitpick comments (1)
packages/core/test/sdk/session/installLocaleCorrector.browser.test.ts (1)

22-22: ⚡ Quick win

Use 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2edbcfd and 429382e.

📒 Files selected for processing (6)
  • packages/core/src/sdk/localization/settings.ts
  • packages/core/src/sdk/localization/useLocalizationConfig.tsx
  • packages/core/src/sdk/session/index.ts
  • packages/core/src/sdk/session/initialSession.ts
  • packages/core/test/sdk/session/getInitialSession.browser.test.ts
  • packages/core/test/sdk/session/installLocaleCorrector.browser.test.ts

@sonar-workflows

Copy link
Copy Markdown

@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

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 429382e and ac542d2.

📒 Files selected for processing (3)
  • packages/core/src/sdk/localization/settings.ts
  • packages/core/src/sdk/session/initialSession.ts
  • packages/core/test/sdk/session/installLocaleCorrector.browser.test.ts

Comment on lines +11 to +20
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 {}
}

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

🧩 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:


🏁 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'))
NODE

Repository: 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.

Suggested change
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.

@lemagnetic
lemagnetic merged commit 75cb5df into dev May 28, 2026
12 checks passed
@lemagnetic
lemagnetic deleted the chore/fix-localization-race-condition branch May 28, 2026 14:39
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.

2 participants