Skip to content

fix: sync IS locale with URL and selectedFacets on navigation#3405

Merged
hellofanny merged 1 commit into
devfrom
fix/is-locale-stale-on-navigation
Jun 29, 2026
Merged

fix: sync IS locale with URL and selectedFacets on navigation#3405
hellofanny merged 1 commit into
devfrom
fix/is-locale-stale-on-navigation

Conversation

@hellofanny

@hellofanny hellofanny commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

Summary

  • @faststore/core: when localization.enabled, derive the locale facet for client-side IS queries from router.locale (via getSettings) instead of session.locale, which can lag after a hard locale switch or back/forward navigation.
  • @faststore/api: prefer ctx.storage.locale (set from trusted selectedFacets) over vtex_segment cookie cultureInfo when building Intelligent Search requests — the cookie can remain stale while the URL and facets already reflect the new locale.

These two changes work together: core sends the correct locale in the GraphQL request; API ensures IS does not override it with a stale segment cookie.

Context

Introduced while working on localized PLP pages (#3401). The bug also affects stores with localization enabled on dev today (locale-prefixed PLPs, search, shelves) even without localized collection slug resolution.

Does not include PLP-specific work (by-linkid, StoreCollection.otherLocales, etc.) — that remains in #3401.

Test plan

  • cd packages/api && pnpm vitest run test/unit/platforms/vtex/clients/search.test.ts
  • With localization.enabled: true, open a locale-prefixed PLP (e.g. /pt-BR/apparel)
  • Switch locale via LocalizationSelector → product grid shows correct translated names immediately
  • Browser back/forward on a localized PLP → product slugs/names stay correct
  • With localization.enabled: false, verify no behavior change on PLP/search pages

PR: https://vtex-dev.atlassian.net/jira/software/c/projects/SFS/boards/1051?selectedIssue=SFS-3242
Made with Cursor

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Localized stores now derive the active locale from the current page URL, enabling immediate updates to language-aware selections during navigation.
  • Bug Fixes

    • Search requests now prioritize the current stored locale over stale cookie data, with a safe fallback when locale is unavailable.
    • Search requests omit the locale parameter when no locale can be determined, preventing invalid locale values.
  • Tests

    • Added unit coverage to verify locale query parameter behavior across precedence and fallback scenarios.

@hellofanny hellofanny requested a review from a team as a code owner June 24, 2026 21:57
@hellofanny hellofanny requested review from gabpaladino and renatomaurovtex and removed request for a team June 24, 2026 21:57
@coderabbitai

coderabbitai Bot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Locale selection now prefers stored VTEX session data in search requests and uses the current router locale for product facet variables when localization is enabled.

Changes

Locale resolution updates

Layer / File(s) Summary
Search locale precedence
packages/api/src/platforms/vtex/clients/search/index.ts, packages/api/test/unit/platforms/vtex/clients/search.test.ts
getSegmentLocale now prefers ctx.storage.locale, falls back to segment.cultureInfo, and the new unit coverage checks the resulting locale query parameter for storage, cookie, and empty inputs.
Localized variables locale source
packages/core/src/sdk/product/useLocalizedVariables.ts
useLocalizedVariables now resolves locale from router.locale when localization is enabled, otherwise it falls back to sessionLocale, and memoizes the derived value across route changes.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • vtex/faststore#3385: Changes VTEX intelligent-search locale derivation in packages/api/src/platforms/vtex/clients/search/index.ts, which is the same client touched here.

Suggested labels

bug

Suggested reviewers

  • lucasfp13
  • ommeirelles
  • renatomaurovtex

Poem

A locale drifted through the stack,
Then found its route and came right back.
Storage spoke, then router chimed,
And facets lined up just in time.
Small keys clicked into place ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% 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 clearly summarizes the main fix: keeping Intelligent Search locale aligned with URL and selected facets during navigation.
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 fix/is-locale-stale-on-navigation

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

@hellofanny hellofanny requested a review from lemagnetic June 24, 2026 21:58
@codesandbox-ci

codesandbox-ci Bot commented Jun 24, 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.

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

🧹 Nitpick comments (1)
packages/core/src/sdk/product/useLocalizedVariables.ts (1)

34-45: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Optional: flatten the memo with an early return.

Logic is correct, but a guard-style early return reads cleaner than the nested if/try.

♻️ Flatter variant
   const locale = useMemo(() => {
-    if (storeConfig.localization?.enabled && typeof window !== 'undefined') {
-      try {
-        return getSettings({
-          url: new URL(router.asPath, window.location.origin),
-        }).locale
-      } catch {
-        return sessionLocale
-      }
-    }
-    return sessionLocale
+    if (!storeConfig.localization?.enabled || typeof window === 'undefined') {
+      return sessionLocale
+    }
+    try {
+      return getSettings({
+        url: new URL(router.asPath, window.location.origin),
+      }).locale
+    } catch {
+      return sessionLocale
+    }
   }, [router.asPath, sessionLocale])

As per path instructions: "Prefer flat conditionals over nested ifs."

🤖 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/product/useLocalizedVariables.ts` around lines 34 - 45,
The locale computation in useLocalizedVariables is correct but uses a nested
if/try structure inside the useMemo callback. Refactor the useMemo logic to use
guard-style early returns instead of nesting, keeping the same fallback behavior
to sessionLocale when localization is disabled or when getSettings throws; use
the existing identifiers useMemo, getSettings, router.asPath, and sessionLocale
to preserve behavior while flattening the control flow.

Source: Path instructions

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

Nitpick comments:
In `@packages/core/src/sdk/product/useLocalizedVariables.ts`:
- Around line 34-45: The locale computation in useLocalizedVariables is correct
but uses a nested if/try structure inside the useMemo callback. Refactor the
useMemo logic to use guard-style early returns instead of nesting, keeping the
same fallback behavior to sessionLocale when localization is disabled or when
getSettings throws; use the existing identifiers useMemo, getSettings,
router.asPath, and sessionLocale to preserve behavior while flattening the
control flow.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 46c92912-22a9-4648-8643-08b988ae98ef

📥 Commits

Reviewing files that changed from the base of the PR and between 961a529 and 7d13777.

📒 Files selected for processing (3)
  • packages/api/src/platforms/vtex/clients/search/index.ts
  • packages/api/test/unit/platforms/vtex/clients/search.test.ts
  • packages/core/src/sdk/product/useLocalizedVariables.ts

When localization is enabled, client-side IS queries could use a stale locale after hard navigation because session.locale and vtex_segment lag behind the URL. Derive the locale facet from router.locale and prefer ctx.storage.locale over the segment cookie when calling Intelligent Search.

Co-authored-by: Cursor <cursoragent@cursor.com>
@hellofanny hellofanny force-pushed the fix/is-locale-stale-on-navigation branch from 7d13777 to f3163a7 Compare June 25, 2026 02:59
@pkg-pr-new

pkg-pr-new Bot commented Jun 25, 2026

Copy link
Copy Markdown

Open in StackBlitz

@faststore/api

npm i https://pkg.pr.new/vtex/faststore/@faststore/api@f3163a7

@faststore/cli

npm i https://pkg.pr.new/vtex/faststore/@faststore/cli@f3163a7

@faststore/components

npm i https://pkg.pr.new/vtex/faststore/@faststore/components@f3163a7

@faststore/core

npm i https://pkg.pr.new/vtex/faststore/@faststore/core@f3163a7

@faststore/diagnostics

npm i https://pkg.pr.new/vtex/faststore/@faststore/diagnostics@f3163a7

@faststore/lighthouse

npm i https://pkg.pr.new/vtex/faststore/@faststore/lighthouse@f3163a7

@faststore/sdk

npm i https://pkg.pr.new/vtex/faststore/@faststore/sdk@f3163a7

@faststore/ui

npm i https://pkg.pr.new/vtex/faststore/@faststore/ui@f3163a7

commit: f3163a7

@sonar-workflows

Copy link
Copy Markdown

@hellofanny hellofanny merged commit 90d644d into dev Jun 29, 2026
13 of 14 checks passed
@hellofanny hellofanny deleted the fix/is-locale-stale-on-navigation branch June 29, 2026 13:14
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