Skip to content

fix: race condition use localization config - #3258

Merged
eduardoformiga merged 4 commits into
canary-v2from
fix/race-condition-use-localization-config
Apr 6, 2026
Merged

eduardoformiga merged 4 commits into
canary-v2from
fix/race-condition-use-localization-config

Conversation

@eduardoformiga

@eduardoformiga eduardoformiga commented Apr 1, 2026 •

Copy link
Copy Markdown
Member

What's the purpose of this pull request?

How it works?

How to test it?

Starters Deploy Preview

References

Checklist

You may erase this after checking them all 😉

PR Title and Commit Messages

  • PR title and commit messages follow the Conventional Commits specification
    • Available prefixes: feat, fix, chore, docs, style, refactor, ci and test

PR Description

  • Added a label according to the PR goal - breaking change, bug, contributing, performance, documentation..

Dependencies

  • Committed the pnpm-lock.yaml file when there were changes to the packages

Documentation

  • PR description
  • For documentation changes, ping @Mariana-Caetano to review and update (Or submit a doc request)

Summary by CodeRabbit

Release Notes

  • Bug Fixes
    • Fixed data persistence initialization to prevent stored data from being overwritten on startup
    • Improved URL matching behavior for development environments and localhost systems

…onfig

- Replaced state management for session with a ref to prevent unnecessary re-renders.
- Updated the effect dependencies to only react to settings changes, improving performance.
- Added logic to handle session updates without triggering re-renders, ensuring smoother localization updates.
…calizationConfig

- Added checks to prevent unnecessary updates when session settings match current localization settings.
- Improved session handling by ensuring that the session reference is consistently used, optimizing performance during the first mount.
…seLocalizationConfig

- Enhanced the first mount logic to prevent unnecessary session updates when no URL binding matches.
- Ensured consistent use of session reference for improved performance and reliability during localization updates.
- Introduced a new function to streamline hostname checks, allowing for easier identification of development and preview environments.
- Simplified the logic in matchURLBinding to enhance readability and maintainability, ensuring proper handling of subdomain and path-based bindings.
- Removed redundant checks related to localhost and development mode, improving overall performance during URL matching.
@eduardoformiga
eduardoformiga requested a review from a team as a code owner April 1, 2026 21:15
@eduardoformiga
eduardoformiga requested review from emersonlaurentino and hellofanny and removed request for a team April 1, 2026 21:15
@coderabbitai

coderabbitai Bot commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

Three files refactored for improved initialization and state management: hostname-checking logic centralized, session state converted to useRef to prevent cascade re-renders, and store hydration timing adjusted to prevent early data overwrites.

Changes

Cohort / File(s) Summary
URL Matching Relaxation
packages/core/src/sdk/localization/match-url.ts
Introduced shouldSkipHostnameCheck() helper to consolidate environment/hostname relaxation logic (development, localhost, .vtex.app). Updated matchURLBinding to conditionally skip hostname and protocol matching; subdomain-binding returns restricted when hostname checks skipped.
Session State Refactor
packages/core/src/sdk/localization/useLocalizationConfig.tsx
Replaced React state initialization of session with useRef tracking. Session–settings sync effect now depends only on settings, reads from sessionRef.current, and avoids re-render-triggered effect re-execution.
Store Hydration Flow
packages/sdk/src/store/persisted.ts
Added hydrated flag to track initial IDB read completion. Initialization now calls handler() immediately (removed debounced call); subscribe side effect only persists to IDB after hydration completes, preventing early overwrites.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • #3256: Directly refactors useLocalizationConfig session handling from state to useRef with synchronized effect dependency changes.
  • #3204: Modifies match-url.ts hostname/protocol matching logic with additional binding-path utilities.
  • #3189: Updates useLocalizationConfig session/settings initialization and tracking mechanisms.

Suggested labels

bug

Suggested reviewers

  • ommeirelles
  • renatamottam
  • hellofanny

Poem

🔧 Refs replace state, hydration waits its turn,
URLs relax their checks with a development burn,
No cascading renders when settings align—
Just syncing and persisting, now perfectly fine! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main objective of the changeset, which is fixing a race condition in the useLocalizationConfig hook by refactoring session state management.

✏️ 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 fix/race-condition-use-localization-config

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.

❤️ Share

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

@codesandbox-ci

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

@emersonlaurentino emersonlaurentino left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM.

@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

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)

37-66: ⚠️ Potential issue | 🔴 Critical

Move all hooks to the top level—this early return violates React Rules of Hooks.

Lines 29–31 contain a conditional early return that skips the useRef and useEffect calls on lines 37–66. React requires all hooks to be called unconditionally at the top level in the same order on every render. Remove the early return and move the settings reconciliation logic inside a useEffect or check settings conditionally within the effects.

As a secondary concern, sessionRef is initialized with the current store snapshot before async IDB hydration completes. If settings changes during hydration, the sync effect uses a stale session value. Consider waiting for or detecting hydration completion before syncing.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/sdk/localization/useLocalizationConfig.tsx` around lines 37
- 66, The hooks (useRef/useEffect) must be called unconditionally in
useLocalizationConfig; remove the early return that prevents them from running
and move the settings reconciliation logic into a dedicated useEffect that runs
when settings changes (e.g., useEffect(() => { ... }, [settings])) so hooks
remain top-level and stable; inside that effect, read the freshest session from
sessionStore (or wait for a session-store "hydrated" flag / subscribe until IDB
hydration completes) instead of relying on the initial sessionRef snapshot to
avoid stale-session syncs, update channel/locale/currency into a newSession,
compare and call sessionStore.set(newSession) only when different.
🧹 Nitpick comments (2)
packages/sdk/src/store/persisted.ts (1)

56-59: Fire-and-forget async call is intentional but consider adding a catch.

Calling handler() without await is correct here (can't block initialization), and the inner getIDB already swallows errors. However, if future changes to handler introduce throwing code paths, an unhandled rejection could slip through. A defensive .catch(() => {}) keeps the pattern explicit.

🛡️ Optional: make the fire-and-forget explicit
-    handler()
+    handler().catch(() => {
+      /* Errors already handled in getIDB; this silences unhandled rejection warnings */
+    })
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/sdk/src/store/persisted.ts` around lines 56 - 59, The immediate call
to handler() is intentionally fire-and-forget but should explicitly handle
rejected promises to avoid future unhandled rejections; update the invocation of
handler() so the returned promise is chained with a .catch handler (e.g.,
handler().catch(() => {})) to explicitly swallow any errors (or log them if
preferred), referencing the handler() call in persisted.ts to locate the change.
packages/core/src/sdk/localization/match-url.ts (1)

16-17: Hoist URL parsing out of the locale scan

new URL(href) and skipHostname are invariant per call but currently recomputed for each locale entry. Hoisting them avoids repeated parsing and keeps the callback focused on per-binding checks.

♻️ Suggested diff
 export function matchURLBinding(href: string) {
   let binding
+  const hostURLObject = new URL(href)
+  const skipHostname = shouldSkipHostnameCheck(hostURLObject.hostname)
   const matchedConfig = Object.entries(config.localization.locales).find(
     ([_, langConfig]: [string, any]) => {
-      const hostURLObject = new URL(href)
-      const skipHostname = shouldSkipHostnameCheck(hostURLObject.hostname)
-
       binding = langConfig.bindings.find(({ url }: { url: string }) => {
         const configURLObject = new URL(url)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/sdk/localization/match-url.ts` around lines 16 - 17, Hoist
the URL parsing and hostname-skip check out of the per-locale scan: compute
const hostURLObject = new URL(href) and const skipHostname =
shouldSkipHostnameCheck(hostURLObject.hostname) once before iterating over
locales (instead of inside the per-binding callback), then pass/use those
precomputed values inside the locale check logic so the callback only performs
per-binding checks.
🤖 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/sdk/localization/match-url.ts`:
- Around line 46-50: The current early return when isSubdomainBinding &&
skipHostname causes all subdomain bindings to fail silently; instead implement a
deterministic behavior: when isSubdomainBinding is true and skipHostname is
true, perform an explicit subdomain comparison using the available host/path
info (e.g., extract subdomain segment from the request host or a provided host
parameter) and compare it to the binding's expected subdomain, returning true
when they match, or otherwise return false and surface the fallback (e.g.,
return a distinct result or allow the caller in useLocalizationConfig.tsx to
log/handle the fallback). Modify the logic in match-url.ts (the block
referencing isSubdomainBinding and skipHostname) to do this deterministic
subdomain check rather than simply returning !skipHostname so configured
subdomain bindings are respected in relaxed-host environments.

In `@packages/core/src/sdk/localization/useLocalizationConfig.tsx`:
- Around line 37-41: sessionRef is seeded from a render-time snapshot but
sessionStore.subscribe() doesn’t replay the current value, so late hydration can
leave sessionRef stale and the sync effect (the effect that applies
locale/channel/currency referenced around line 66) never reruns; fix by making
the subscribe callback not only update sessionRef.current but also trigger a
React state change (or set a "hydrated" flag) when a different session arrives
so the sync effect will rerun once the first hydrated session lands, or
alternatively delay running the sync effect until you detect sessionStore has
finished hydration; update the subscribe handler in useLocalizationConfig (the
sessionRef / sessionStore subscribe logic) to compare newSession to
sessionRef.current and call setState/setHydrated to force one rerun when they
differ.

---

Outside diff comments:
In `@packages/core/src/sdk/localization/useLocalizationConfig.tsx`:
- Around line 37-66: The hooks (useRef/useEffect) must be called unconditionally
in useLocalizationConfig; remove the early return that prevents them from
running and move the settings reconciliation logic into a dedicated useEffect
that runs when settings changes (e.g., useEffect(() => { ... }, [settings])) so
hooks remain top-level and stable; inside that effect, read the freshest session
from sessionStore (or wait for a session-store "hydrated" flag / subscribe until
IDB hydration completes) instead of relying on the initial sessionRef snapshot
to avoid stale-session syncs, update channel/locale/currency into a newSession,
compare and call sessionStore.set(newSession) only when different.

---

Nitpick comments:
In `@packages/core/src/sdk/localization/match-url.ts`:
- Around line 16-17: Hoist the URL parsing and hostname-skip check out of the
per-locale scan: compute const hostURLObject = new URL(href) and const
skipHostname = shouldSkipHostnameCheck(hostURLObject.hostname) once before
iterating over locales (instead of inside the per-binding callback), then
pass/use those precomputed values inside the locale check logic so the callback
only performs per-binding checks.

In `@packages/sdk/src/store/persisted.ts`:
- Around line 56-59: The immediate call to handler() is intentionally
fire-and-forget but should explicitly handle rejected promises to avoid future
unhandled rejections; update the invocation of handler() so the returned promise
is chained with a .catch handler (e.g., handler().catch(() => {})) to explicitly
swallow any errors (or log them if preferred), referencing the handler() call in
persisted.ts to locate the change.
🪄 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: 7c1b1d0b-88e5-4c56-bf0b-092b02eaefaa

📥 Commits

Reviewing files that changed from the base of the PR and between 641a9f8 and 1e12ab0.

📒 Files selected for processing (3)
  • packages/core/src/sdk/localization/match-url.ts
  • packages/core/src/sdk/localization/useLocalizationConfig.tsx
  • packages/sdk/src/store/persisted.ts

Comment on lines +46 to 50
// Subdomain bindings rely on hostname, so when the hostname check
// is skipped we can only match path-based bindings.
if (isSubdomainBinding) {
return true
return !skipHostname
}

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 | 🟠 Major

Subdomain bindings are effectively disabled in relaxed-host environments

At Line 49, return !skipHostname makes every subdomain binding fail on localhost/development/.vtex.app. In the current caller (packages/core/src/sdk/localization/useLocalizationConfig.tsx, Lines 126-132), that silently falls back to default settings, so configured locale/binding can be ignored without signal. Please keep a deterministic subdomain match path (or explicitly surface that fallback) instead of returning no match.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/sdk/localization/match-url.ts` around lines 46 - 50, The
current early return when isSubdomainBinding && skipHostname causes all
subdomain bindings to fail silently; instead implement a deterministic behavior:
when isSubdomainBinding is true and skipHostname is true, perform an explicit
subdomain comparison using the available host/path info (e.g., extract subdomain
segment from the request host or a provided host parameter) and compare it to
the binding's expected subdomain, returning true when they match, or otherwise
return false and surface the fallback (e.g., return a distinct result or allow
the caller in useLocalizationConfig.tsx to log/handle the fallback). Modify the
logic in match-url.ts (the block referencing isSubdomainBinding and
skipHostname) to do this deterministic subdomain check rather than simply
returning !skipHostname so configured subdomain bindings are respected in
relaxed-host environments.

Comment on lines +37 to +41
const sessionRef = useRef(sessionStore.read() ?? sessionStore.readInitial())

useEffect(() => {
return sessionStore.subscribe((newSession) => {
setSession(newSession)
sessionRef.current = newSession

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 | 🔴 Critical

Late session hydration still reopens the race.

Line 37 seeds the ref from a render-time snapshot, but packages/sdk/src/store/base.ts:42-48 does not replay the current value on subscribe(). Since sessionStore is persisted (packages/sdk/src/session/index.ts:70-74, packages/sdk/src/store/composed.ts:7-22), hydration can arrive after mount with a different session. Line 41 only mutates the ref, and Line 66 prevents the sync effect from running again, so locale/channel/currency can still be applied against stale session data. Trigger one rerun when the first hydrated session lands, or delay this effect until hydration completes.

Also applies to: 45-66

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/sdk/localization/useLocalizationConfig.tsx` around lines 37
- 41, sessionRef is seeded from a render-time snapshot but
sessionStore.subscribe() doesn’t replay the current value, so late hydration can
leave sessionRef stale and the sync effect (the effect that applies
locale/channel/currency referenced around line 66) never reruns; fix by making
the subscribe callback not only update sessionRef.current but also trigger a
React state change (or set a "hydrated" flag) when a different session arrives
so the sync effect will rerun once the first hydrated session lands, or
alternatively delay running the sync effect until you detect sessionStore has
finished hydration; update the subscribe handler in useLocalizationConfig (the
sessionRef / sessionStore subscribe logic) to compare newSession to
sessionRef.current and call setState/setHydrated to force one rerun when they
differ.

@eduardoformiga
eduardoformiga merged commit ab1eff8 into canary-v2 Apr 6, 2026
3 checks passed
@eduardoformiga
eduardoformiga deleted the fix/race-condition-use-localization-config branch April 6, 2026 14:48
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.

3 participants