Skip to content

feat: use locale from Next.js on PLP search instead of discovery.config - #3207

Merged
lemagnetic merged 2 commits into
feat/multilanguagefrom
feat/search-dynamic-locale
Feb 19, 2026
Merged

lemagnetic merged 2 commits into
feat/multilanguagefrom
feat/search-dynamic-locale

Conversation

@lemagnetic

@lemagnetic lemagnetic commented Feb 12, 2026 •

Copy link
Copy Markdown
Contributor

What's the purpose of this pull request?

On the PLP (Product Listing Page), the locale used for search and product gallery came from discovery.config (session), which is fixed per environment. In multi-language stores, this prevented search and products from matching the current route’s language. This PR makes the PLP use the page locale from Next.js so search and content align with the URL locale.

How it works?

  • In [...slug].tsx, the locale already available in Next’s getStaticProps is passed into fetchServerManyProducts.
  • In fetchProductGallerySSR.ts, fetchServerManyProducts now accepts locale as a parameter and no longer uses storeConfig.session.locale. PLP search/SSR for the gallery uses the route locale (e.g. /en-US/..., /pt-BR/...).

How to test it?

N/A

Starters Deploy Preview

N/A

References

Jira

Summary by CodeRabbit

  • Refactor

    • Product gallery server-side data fetching now consistently accepts and propagates locale so region-specific product data is retrieved during SSR.
  • Bug Fix / Improvement

    • Product page data queries now include locale, improving accuracy of displayed products for different regions.

@lemagnetic
lemagnetic requested a review from a team as a code owner February 12, 2026 14:01
@lemagnetic
lemagnetic requested review from eduardoformiga and lucasfp13 and removed request for a team February 12, 2026 14:01
@coderabbitai

coderabbitai Bot commented Feb 12, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds locale propagation for server-side product gallery fetching: page-level getStaticProps passes locale into serverManyProductsVariables, and fetchServerManyProducts now accepts and uses locale when building GraphQL query variables.

Changes

Cohort / File(s) Summary
Page — slug route
packages/core/src/pages/[...slug].tsx
Passes locale into serverManyProductsVariables inside getStaticProps, adding locale to product fetch parameters.
Product gallery SSR util
packages/core/src/utils/fetchProductGallerySSR.ts
Function signature fetchServerManyProducts updated to require locale: string; locale is used in selected facets and result GraphQL variables.
Alternate slug page variant
packages/core/src/pages/[slug]/p.tsx
Includes { key: 'locale', value: locale } in GraphQL locator variables alongside slug, tightening query specificity.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • eduardoformiga
  • lucasfp13
  • lariciamota

Poem

A locale travels down the line,
From page to query, crisp and fine,
Each product now in proper tongue,
A little string — the globe among. 🌐

🚥 Pre-merge checks | ✅ 3 | ❌ 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 (3 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 change: using Next.js locale on PLP search instead of discovery.config, which is directly supported by all three modified files that route locale through the product gallery fetch.
Merge Conflict Detection ✅ Passed ✅ No merge conflicts detected when merging into feat/multilanguage

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/search-dynamic-locale

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 Feb 12, 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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/core/src/utils/fetchProductGallerySSR.ts (1)

46-65: ⚠️ Potential issue | 🟠 Major

locale can be undefined at the call site — runtime risk.

Next.js GetStaticPropsContext['locale'] is typed as string | undefined. The caller in [...slug].tsx passes it directly without a fallback, but this parameter is typed as locale: string (required, non-optional). If locale is undefined at runtime (e.g., no i18n config in next.config.js), the facet { key: 'locale', value: undefined } will be sent to the GraphQL API, likely producing unexpected results.

Consider either:

  1. Adding a fallback at the call site (preferred, keeps this function strict), or
  2. Making the parameter optional with a sensible default from storeConfig.session.locale.
Option 2: fallback inside fetchServerManyProducts
-  locale,
+  locale = storeConfig.session.locale,
 }: {
   itemsPerPage: number
   sort: SearchState['sort']
   term: string
   selectedFacets?: {
     key: string
     value: string
   }[]
   sponsoredCount?: number
   filter?: boolean
-  locale: string
+  locale?: string
 }) {

This preserves backward compatibility and ensures a safe default when locale isn't available from the Next.js context.

packages/core/src/pages/[...slug].tsx (1)

188-196: ⚠️ Potential issue | 🟠 Major

Pass a fallback for locale to prevent undefined propagation.

locale from GetStaticPropsContext is string | undefined. Without a fallback, this silently passes undefined to fetchServerManyProducts, which expects string. TypeScript should flag this if strict checks are on, but regardless, a runtime guard is warranted.

Suggested fix
     selectedFacets: data?.collection?.meta.selectedFacets,
-    locale,
+    locale: locale ?? storeConfig.session.locale,
   })

This keeps the route locale as the primary source while falling back to the session locale from discovery.config — the previous behavior — when locale is unavailable.

@lemagnetic
lemagnetic force-pushed the feat/search-dynamic-locale branch from 15e8994 to 83aaec7 Compare February 13, 2026 15:32
@hellofanny

Copy link
Copy Markdown
Contributor

@lemagnetic
breadcrumb is not localized yet.
image

/src/pages/[slug]/p.tsx
We need to pass the locale in the PDP query, maybe like that?
Can you add please 🏆
image

@hellofanny

Copy link
Copy Markdown
Contributor

actually this fix will reflect for the product seo info too, just make sure to double check it, ok? Thanks
image

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/core/src/utils/fetchProductGallerySSR.ts (1)

46-65: ⚠️ Potential issue | 🔴 Critical

locale parameter accepts string but receives string | undefined from Next.js context.

Next.js's getStaticProps context types locale as string | undefined, yet fetchServerManyProducts requires a non-optional string. In [...slug].tsx, locale is passed directly without validation or fallback, creating a type safety gap.

Make the function resilient to undefined:

Suggested fix
-  locale,
+  locale: localeParam,
 }: {
   ...
-  locale: string
+  locale?: string
 }) {
-  let { channel } = storeConfig.session
+  let { channel, locale: defaultLocale } = storeConfig.session
+  const locale = localeParam ?? defaultLocale

This keeps the fallback logic near its usage point and prevents runtime errors if a caller forgets to coerce undefined.

packages/core/src/pages/[slug]/p.tsx (1)

306-311: ⚠️ Potential issue | 🟠 Major

Pass locale to URL construction to ensure canonical URLs reflect the correct locale.

The locale parameter from getStaticProps is correctly passed to the server query but not to getStoreURL() (lines 129, 376) or structured data components. This breaks canonical URL consistency across locales and omits language declarations in ProductJsonLd and BreadcrumbJsonLd. Either:

  • Pass locale to getStoreURL() and update its signature, or
  • Build canonical URLs using the locale-aware URL directly from the GraphQL response, ensuring breadcrumb paths and structured data include the inLanguage attribute.
🤖 Fix all issues with AI agents
In `@packages/core/src/pages/`[slug]/p.tsx:
- Around line 326-331: The GraphQL locator currently includes { key: 'locale',
value: locale } where Next.js context.locale can be undefined, violating the
non-null IStoreSelectedFacet contract; update the variables construction so the
locale value falls back to storeConfig.session.locale when locale is undefined
(e.g., use locale ?? storeConfig.session.locale) so the locator array passed to
the query always contains a non-null string for the 'locale' facet, and ensure
this change is applied where variables are built for the query referenced in
this file (the locator array around slug and locale).

Comment on lines +326 to +331
variables: {
locator: [
{ key: 'slug', value: slug },
{ key: 'locale', value: locale },
],
},

@coderabbitai coderabbitai Bot Feb 13, 2026 •

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

locale can be undefined — will break the GraphQL IStoreSelectedFacet contract.

Next.js types context.locale as string | undefined (undefined when i18n is not configured, or on the default locale depending on config). Passing it directly as value: locale means you could send { key: 'locale', value: undefined } into a [IStoreSelectedFacet!]! field that expects non-null string values. This will either cause a GraphQL validation error or silently corrupt the query.

Add a fallback to storeConfig.session.locale:

Suggested fix
       variables: {
         locator: [
           { key: 'slug', value: slug },
-          { key: 'locale', value: locale },
+          { key: 'locale', value: locale ?? storeConfig.session.locale },
         ],
       },
🤖 Prompt for AI Agents
In `@packages/core/src/pages/`[slug]/p.tsx around lines 326 - 331, The GraphQL
locator currently includes { key: 'locale', value: locale } where Next.js
context.locale can be undefined, violating the non-null IStoreSelectedFacet
contract; update the variables construction so the locale value falls back to
storeConfig.session.locale when locale is undefined (e.g., use locale ??
storeConfig.session.locale) so the locator array passed to the query always
contains a non-null string for the 'locale' facet, and ensure this change is
applied where variables are built for the query referenced in this file (the
locator array around slug and locale).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

In this project, i18n is always configured in next.config.js (lines 23-33). When localesSettings.enabled is false, we still pass a minimal i18n config with locales and defaultLocale from storeConfig.session.locale. So there's no path where i18n is absent, and Next.js will always provide locale in getStaticProps. The locale?: string type comes from Next.js' generic API, but in our setup it's always defined.

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.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check next.config.js to verify the i18n configuration claim
cat next.config.js | head -n 40

Length of output: 46


🏁 Script executed:

#!/bin/bash
# Find next.config.js files in the repository
fd -t f "next.config.js"

# Also check for next.config.ts
fd -t f "next.config.ts"

Length of output: 28


🏁 Script executed:

#!/bin/bash
# Read next.config.js with line numbers to verify the i18n configuration
cat -n packages/core/next.config.js | head -n 50

Length of output: 2223


@lemagnetic You're absolutely right! I can see in packages/core/next.config.js lines 23-33 that i18n is indeed always configured in FastStore:

  • When localesSettings.enabled is true: configures with multiple locales
  • When localesSettings.enabled is false: still configures i18n with [storeConfig.session.locale] as the single locale

This means Next.js will always provide locale in getStaticProps, so there's no risk of it being undefined in your setup. My concern was based on the generic Next.js API surface but doesn't apply to FastStore's architecture. Thank you for the clarification!


🧬 Code Graph Analysis Results

[packages/core/src/pages/[...slug].tsx:113-240]

export const getStaticProps: GetStaticProps<
  Props,
  { slug: string[] },
  PreviewData
> = async ({ params, previewData, locale }) => {
  const slug = params?.slug.join('/') ?? ''
  const rewrites = (await storeConfig.rewrites?.()) ?? []

  const [
    globalSectionsPromise,
    globalSectionsHeaderPromise,
    globalSectionsFooterPromise,
  ] = getGlobalSectionsData(previewData, locale)

  const [
    serverData,
    globalSections,
    globalSectionsHeader,
    globalSectionsFooter,
  ] = await Promise.all([
    getDynamicContent({ pageType: slug }),
    globalSectionsPromise,
    globalSectionsHeaderPromise,
    globalSectionsFooterPromise,
  ])

  const globalSectionsResult = injectGlobalSections({
    globalSections,
    globalSectionsHeader,
    globalSectionsFooter,
  })

  return {
    props: {
      page: landingPage,
      globalSections: globalSectionsResult,
      type: 'page',
      slug,
      serverData,
    },
  }
}

[packages/core/src/sdk/localization/useLocalizationConfig.tsx:131-138]

export const getStoreURL = () => {
  // If localization is not enabled, use storeUrl from config
  if (!config.localization?.enabled === true) {
    return config.storeUrl
  }

  return getSettings().storeURL
}

[packages/core/src/server/cms/global.ts:35-78] (excerpt showing global sections injection behavior)

export function injectGlobalSections({
  globalSections,
  globalSectionsHeader,
  globalSectionsFooter,
}: InjectGlobalSectionsProps) {
  if (
    !globalSections ||
    !globalSections.sections ||
    globalSections.sections.length === 0
  ) {
    console.warn(
      'Global Sections content type was not found or has no sections. Returning minimal structure for development.'
    )
    return createMinimalGlobalSections({
      globalSectionsHeader,
      globalSectionsFooter,
      settings: globalSections?.settings,
    })
  }

  const headerSections = globalSectionsHeader?.sections || []
  const footerSections = globalSectionsFooter?.sections || []

  return {
    ...globalSections,
    sections: [
      ...globalSections.sections.filter((s) => s.name !== 'Children'),
      ...headerSections,
      globalSections.sections.find((s) => s.name === 'Children')!,
      ...footerSections,
    ],
  }
}

[packages/core/src/pages/[...slug].tsx:113-240] (note: adjacent/related content shows locale usage in getStaticProps; see above)


✏️ Learnings added
Learnt from: lemagnetic
Repo: vtex/faststore PR: 3207
File: packages/core/src/pages/[slug]/p.tsx:326-331
Timestamp: 2026-02-19T18:52:26.613Z
Learning: In FastStore (packages/core), i18n is always configured in next.config.js (lines 23-33). When localesSettings.enabled is false, the config still includes a minimal i18n setup with locales: [storeConfig.session.locale] and defaultLocale: storeConfig.session.locale. This guarantees that Next.js context.locale is always defined in getStaticProps, never undefined.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: lucasfp13
Repo: vtex/faststore PR: 3179
File: packages/core/src/pages/[slug]/p.tsx:109-118
Timestamp: 2026-01-25T21:31:56.033Z
Learning: In `packages/core/src/pages/[slug]/p.tsx`, the `minPriceFractionDigits` configuration for SEO product price formatting does not need to support `0` as a valid value. The truthy check is intentional—when undefined or 0, the code falls back to default `.toString()` behavior.

Learnt from: lariciamota
Repo: vtex/faststore PR: 3192
File: packages/core/src/components/ui/Breadcrumb/Breadcrumb.tsx:9-9
Timestamp: 2026-01-30T17:18:19.967Z
Learning: In the FastStore codebase, when removing hardcoded messages (as part of the multilanguage/CMS centralization effort), components intentionally do not provide fallback defaults for text props like `alt`, `title`, or labels. This forces all UI text to come from CMS configuration files (sections.json, content-types.json), even if it means props may be undefined at runtime when CMS values are missing.

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

LGTM!

Product content translated and breadcrumb too ✅

Image Image Image

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