Repository navigation
feat: use locale from Next.js on PLP search instead of discovery.config - #3207
Conversation
WalkthroughAdds 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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
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. 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. |
There was a problem hiding this comment.
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
localecan beundefinedat the call site — runtime risk.Next.js
GetStaticPropsContext['locale']is typed asstring | undefined. The caller in[...slug].tsxpasses it directly without a fallback, but this parameter is typed aslocale: string(required, non-optional). Iflocaleisundefinedat runtime (e.g., no i18n config innext.config.js), the facet{ key: 'locale', value: undefined }will be sent to the GraphQL API, likely producing unexpected results.Consider either:
- Adding a fallback at the call site (preferred, keeps this function strict), or
- 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 | 🟠 MajorPass a fallback for
localeto preventundefinedpropagation.
localefromGetStaticPropsContextisstring | undefined. Without a fallback, this silently passesundefinedtofetchServerManyProducts, which expectsstring. 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 — whenlocaleis unavailable.
15e8994 to
83aaec7
Compare
|
@lemagnetic
|
|
actually this fix will reflect for the product seo info too, just make sure to double check it, ok? Thanks |
There was a problem hiding this comment.
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
localeparameter acceptsstringbut receivesstring | undefinedfrom Next.js context.Next.js's
getStaticPropscontext typeslocaleasstring | undefined, yetfetchServerManyProductsrequires a non-optionalstring. In[...slug].tsx,localeis 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 ?? defaultLocaleThis 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 | 🟠 MajorPass locale to URL construction to ensure canonical URLs reflect the correct locale.
The
localeparameter fromgetStaticPropsis correctly passed to the server query but not togetStoreURL()(lines 129, 376) or structured data components. This breaks canonical URL consistency across locales and omits language declarations inProductJsonLdandBreadcrumbJsonLd. Either:
- Pass
localetogetStoreURL()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
inLanguageattribute.
🤖 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).
| variables: { | ||
| locator: [ | ||
| { key: 'slug', value: slug }, | ||
| { key: 'locale', value: locale }, | ||
| ], | ||
| }, |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🧩 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.enabledis true: configures with multiple locales - When
localesSettings.enabledis 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.






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?
[...slug].tsx, thelocalealready available in Next’sgetStaticPropsis passed intofetchServerManyProducts.fetchProductGallerySSR.ts,fetchServerManyProductsnow acceptslocaleas a parameter and no longer usesstoreConfig.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
Bug Fix / Improvement