Repository navigation
feat: [CP-1182] handling locales on the preview flow - #3260
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughReplaces standalone Changes
Sequence Diagram(s)sequenceDiagram
participant Browser
participant NextJS as Next.js
participant ContentSvc as ContentService
participant ClientCP as ClientCP
Browser->>NextJS: Request page (SSG/SSR)
NextJS->>NextJS: build contentContext { previewData, locale }
NextJS->>ContentSvc: getGlobalSectionsData(contentContext)
ContentSvc->>ClientCP: getSingleContent(...cmsOptions, locale: effectiveLocale)
ClientCP-->>ContentSvc: CMS response
ContentSvc-->>NextJS: resolved content (sections / params)
NextJS-->>Browser: render page with injected global sections
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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. |
after attribute as string instead of integer (#3245)after attribute as string instead of integer
a2d8af3 to
3bf7514
Compare
after attribute as string instead of integerThere 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 (1)
packages/core/src/components/templates/LandingPage/LandingPage.tsx (1)
117-119:⚠️ Potential issue | 🔴 CriticalCritical bug:
findcallback never returns a value.The arrow function uses curly braces without a
returnstatement, sopageBySlugwill always beundefined. The comparison result is evaluated but discarded.🐛 Fix: Use implicit return or add return statement
const pageBySlug = cmsData['landingPage'].find((page: any) => { - slug === page.settings?.seo?.slug - }) + return slug === page.settings?.seo?.slug + })Or use implicit return:
- const pageBySlug = cmsData['landingPage'].find((page: any) => { - slug === page.settings?.seo?.slug - }) + const pageBySlug = cmsData['landingPage'].find( + (page: any) => slug === page.settings?.seo?.slug + )🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/components/templates/LandingPage/LandingPage.tsx` around lines 117 - 119, The find callback for cmsData['landingPage'] never returns a value so pageBySlug is always undefined; fix the callback in the pageBySlug assignment (the arrow passed to .find) to return the comparison result — either use an implicit return like (page: any) => slug === page.settings?.seo?.slug or add an explicit return statement inside the existing function body — ensure the symbol pageBySlug and the .find callback on cmsData['landingPage'] are updated accordingly.
🧹 Nitpick comments (3)
packages/core/src/pages/pvt/account/orders/index.tsx (1)
138-141: Behavior is correct; consider extracting a sharedcontentContexthelper.The same
{ previewData, locale }assembly now appears in several account SSR pages; a tiny helper can reduce drift in future updates.Also applies to: 155-155
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/pages/pvt/account/orders/index.tsx` around lines 138 - 141, The repeated assembly of { previewData, locale } into a local contentContext object is duplicated across account SSR pages; extract a small shared helper function (e.g., createContentContext or getContentContext) that takes the Next.js context (or previewData and locale) and returns { previewData, locale }, then replace the inline const contentContext = { previewData: context.previewData, locale: context.locale } in this file (and the other account SSR pages) with a call to that helper to centralize the shape and avoid future drift.packages/core/src/server/content/service.ts (1)
207-210: Prefer type narrowing over assertion for nested filters.This cast weakens type safety in a core path. Please switch to a type guard (or tighten
ContentOptions['cmsOptions']['filters']typing) sonestedis inferred withoutas.♻️ Suggested refactor
+type FiltersContainer = { filters?: Record<string, unknown> } + +function hasNestedFilters(value: unknown): value is FiltersContainer { + return typeof value === 'object' && value !== null && 'filters' in value +} + if ('filters' in cmsOptions && cmsOptions.filters) { - const nested = ( - cmsOptions.filters as { filters?: Record<string, unknown> } - ).filters + const nested = hasNestedFilters(cmsOptions.filters) + ? cmsOptions.filters.filters + : undefined const seo = nested?.['settings.seo.slug']As per coding guidelines "TypeScript files: Ensure type safety and avoid type assertions when possible".
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/server/content/service.ts` around lines 207 - 210, The code currently uses a type assertion on cmsOptions.filters to access nested.filters which weakens type safety; replace the assertion with a type guard or narrowed check so nested is inferred correctly (e.g. add a predicate like isFiltersWithNested(value): value is { filters?: Record<string, unknown> } and use if (isFiltersWithNested(cmsOptions.filters)) { const nested = cmsOptions.filters.filters; const seo = nested?.['settings.seo.slug']; } or alternatively tighten the ContentOptions['cmsOptions']['filters'] type so cmsOptions.filters already has the { filters?: Record<string, unknown> } shape; update usage sites referencing cmsOptions.filters, nested and 'settings.seo.slug' accordingly.packages/core/src/pages/checkout.tsx (1)
48-58: Type generic inconsistency with other page files.This file uses
Locatoras thegetStaticPropsgeneric type parameter, while other pages (e.g.,index.tsx,[slug]/p.tsx,[...slug].tsx) usePreviewData. For consistency across the codebase, consider usingPreviewDatahere as well.export const getStaticProps: GetStaticProps< Props, Record<string, string>, - Locator + PreviewData > = async ({ previewData, locale }) => {You'd also need to add the import:
import type { PreviewData } from 'src/server/content/types'🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/pages/checkout.tsx` around lines 48 - 58, Change the getStaticProps generic parameter from Locator to PreviewData to match other pages: update the signature export const getStaticProps: GetStaticProps<Props, Record<string, string>, PreviewData> = async (...) and add the import line for PreviewData (import type { PreviewData } from 'src/server/content/types') at the top of the file so the type is available; ensure no other references rely on Locator in this file and adjust them to PreviewData if needed.
🤖 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/components/templates/LandingPage/LandingPage.tsx`:
- Around line 141-145: The conditional is wrapping filters twice: in
LandingPage.tsx where you set the object with key filters (used as
ContentParams.filters), remove the inner `filters` wrapper so the property is a
flat Record; change the branch that currently produces `{ filters: {
'settings.seo.slug': `/${slug}` } }` to instead produce `{ 'settings.seo.slug':
`/${slug}` }` (i.e., assign `filters: contentContext.previewData?.contentType
=== 'landingPage' ? undefined : { 'settings.seo.slug': `/${slug}` }`), leaving
all other logic (previewData check, slug variable) unchanged.
---
Outside diff comments:
In `@packages/core/src/components/templates/LandingPage/LandingPage.tsx`:
- Around line 117-119: The find callback for cmsData['landingPage'] never
returns a value so pageBySlug is always undefined; fix the callback in the
pageBySlug assignment (the arrow passed to .find) to return the comparison
result — either use an implicit return like (page: any) => slug ===
page.settings?.seo?.slug or add an explicit return statement inside the existing
function body — ensure the symbol pageBySlug and the .find callback on
cmsData['landingPage'] are updated accordingly.
---
Nitpick comments:
In `@packages/core/src/pages/checkout.tsx`:
- Around line 48-58: Change the getStaticProps generic parameter from Locator to
PreviewData to match other pages: update the signature export const
getStaticProps: GetStaticProps<Props, Record<string, string>, PreviewData> =
async (...) and add the import line for PreviewData (import type { PreviewData }
from 'src/server/content/types') at the top of the file so the type is
available; ensure no other references rely on Locator in this file and adjust
them to PreviewData if needed.
In `@packages/core/src/pages/pvt/account/orders/index.tsx`:
- Around line 138-141: The repeated assembly of { previewData, locale } into a
local contentContext object is duplicated across account SSR pages; extract a
small shared helper function (e.g., createContentContext or getContentContext)
that takes the Next.js context (or previewData and locale) and returns {
previewData, locale }, then replace the inline const contentContext = {
previewData: context.previewData, locale: context.locale } in this file (and the
other account SSR pages) with a call to that helper to centralize the shape and
avoid future drift.
In `@packages/core/src/server/content/service.ts`:
- Around line 207-210: The code currently uses a type assertion on
cmsOptions.filters to access nested.filters which weakens type safety; replace
the assertion with a type guard or narrowed check so nested is inferred
correctly (e.g. add a predicate like isFiltersWithNested(value): value is {
filters?: Record<string, unknown> } and use if
(isFiltersWithNested(cmsOptions.filters)) { const nested =
cmsOptions.filters.filters; const seo = nested?.['settings.seo.slug']; } or
alternatively tighten the ContentOptions['cmsOptions']['filters'] type so
cmsOptions.filters already has the { filters?: Record<string, unknown> } shape;
update usage sites referencing cmsOptions.filters, nested and
'settings.seo.slug' accordingly.
🪄 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: 1535b817-4f66-4b2b-9f00-38838ff516ab
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamland included by none
📒 Files selected for processing (23)
packages/core/package.jsonpackages/core/src/components/cms/GlobalSections.tsxpackages/core/src/components/templates/LandingPage/LandingPage.tsxpackages/core/src/experimental/myAccountServerSideProps.tspackages/core/src/experimental/searchServerSideFunctions/getServerSideProps.tspackages/core/src/experimental/searchServerSideFunctions/getStaticProps.tspackages/core/src/pages/404.tsxpackages/core/src/pages/500.tsxpackages/core/src/pages/[...slug].tsxpackages/core/src/pages/[slug]/p.tsxpackages/core/src/pages/api/preview.tspackages/core/src/pages/checkout.tsxpackages/core/src/pages/index.tsxpackages/core/src/pages/login.tsxpackages/core/src/pages/pvt/account/403.tsxpackages/core/src/pages/pvt/account/404.tsxpackages/core/src/pages/pvt/account/orders/[id].tsxpackages/core/src/pages/pvt/account/orders/index.tsxpackages/core/src/pages/pvt/account/profile.tsxpackages/core/src/pages/pvt/account/security.tsxpackages/core/src/pages/pvt/account/user-details.tsxpackages/core/src/server/content/service.tspackages/core/src/server/content/types.ts
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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/server/content/service.ts`:
- Around line 206-213: Remove the unnecessary type assertion on
cmsOptions.filters: after the `'filters' in cmsOptions` check, use
cmsOptions.filters directly (no `as Record<string, unknown>`) when assigning to
the local variable (e.g., const filters = cmsOptions.filters), then access
filters['settings.seo.slug'] and set params.slug as currently done (see
cmsOptions, filters, seo, params.slug).
In `@packages/core/test/server/content/service.test.ts`:
- Around line 19-44: Add a new test in the convertOptionsToParams describe block
that verifies locale is forwarded into client params: use
getServiceInternals(new ContentService()) to create service, call
service.createContentOptions with contentType (e.g., 'landingPage') and locale
set (e.g., 'en-US'), then call service.convertOptionsToParams(options) and
assert that the returned params include the same locale (e.g.,
expect(params.locale).toBe('en-US')). Ensure you include a case where
slug/filters can be present or omitted as needed to mirror existing tests and
reference convertOptionsToParams, createContentOptions, and ContentService to
locate the code.
🪄 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: dc6536aa-a4c4-4e18-8748-81f9de10243a
📒 Files selected for processing (3)
packages/core/src/components/templates/LandingPage/LandingPage.tsxpackages/core/src/server/content/service.tspackages/core/test/server/content/service.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/core/src/components/templates/LandingPage/LandingPage.tsx
| describe('convertOptionsToParams', () => { | ||
| it('maps a flat SEO slug filter to the client-cp slug param', () => { | ||
| const service = getServiceInternals(new ContentService()) | ||
| const options = service.createContentOptions({ | ||
| contentType: 'landingPage', | ||
| filters: { 'settings.seo.slug': '/summer-sale' }, | ||
| }) | ||
|
|
||
| const params = service.convertOptionsToParams(options) | ||
|
|
||
| expect(params.slug).toBe('summer-sale') | ||
| }) | ||
|
|
||
| it('keeps an explicit slug when filters also include settings.seo.slug', () => { | ||
| const service = getServiceInternals(new ContentService()) | ||
| const options = service.createContentOptions({ | ||
| contentType: 'landingPage', | ||
| slug: 'summer-sale', | ||
| filters: { 'settings.seo.slug': '/other-slug' }, | ||
| }) | ||
|
|
||
| const params = service.convertOptionsToParams(options) | ||
|
|
||
| expect(params.slug).toBe('summer-sale') | ||
| }) | ||
| }) |
There was a problem hiding this comment.
Add a locale mapping test for convertOptionsToParams.
service.ts now forwards locale into CP params, but this suite doesn’t assert that behavior yet.
✅ Suggested test addition
describe('convertOptionsToParams', () => {
+ it('forwards locale to client-cp params', () => {
+ const service = getServiceInternals(new ContentService())
+ const options = service.createContentOptions({
+ contentType: 'landingPage',
+ locale: 'pt-BR',
+ })
+
+ const params = service.convertOptionsToParams(options)
+
+ expect(params.locale).toBe('pt-BR')
+ })
+
it('maps a flat SEO slug filter to the client-cp slug param', () => {
const service = getServiceInternals(new ContentService())🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/core/test/server/content/service.test.ts` around lines 19 - 44, Add
a new test in the convertOptionsToParams describe block that verifies locale is
forwarded into client params: use getServiceInternals(new ContentService()) to
create service, call service.createContentOptions with contentType (e.g.,
'landingPage') and locale set (e.g., 'en-US'), then call
service.convertOptionsToParams(options) and assert that the returned params
include the same locale (e.g., expect(params.locale).toBe('en-US')). Ensure you
include a case where slug/filters can be present or omitted as needed to mirror
existing tests and reference convertOptionsToParams, createContentOptions, and
ContentService to locate the code.
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 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/server/content/types.ts`:
- Around line 27-30: The ContentOptions interface currently carries locale but
the nested cmsOptions: Options type does not, so locale can be lost when calling
getPage(options.cmsOptions); update the contract so locale is preserved by
either adding locale?: string to the Options type or changing ContentOptions to
require cmsOptions: Options & { locale?: string } and then update usages of
getPage, getContent, or other functions that accept cmsOptions (e.g., getPage)
to expect and forward the locale field; ensure all call sites construct or pass
a cmsOptions object that includes locale to maintain propagation through the
non-CP path.
In `@packages/core/test/pages/api/preview.test.ts`:
- Around line 54-65: Test currently expects preview session data to include a
locale, but preview cookies should remain locator-only; update the assertion on
res.setPreviewData in preview.test.ts to remove the locale field and only
include the locator keys (contentType, documentId, versionId) in the first
argument, while keeping the second argument (options: { maxAge: 3600, path: '/'
}) unchanged; ensure you reference the res.setPreviewData call and adjust the
expected payload to assert locator-only session data.
- Around line 16-17: The test doubles use unsafe casts (e.g., "as unknown as"
and "as never"); update createResponse() to return a properly typed mock such as
Pick<NextApiResponse, 'status'|'setHeader'|'json'|'end'> instead of casting,
change mock return values currently typed as {} as never to an explicit typed
object matching the mocked function's return, and type request doubles as
Partial<NextApiRequest> or Pick<NextApiRequest,'query'> where used (replace
double-casts around the request objects). Locate the helper createResponse, the
places creating mock return values, and the request mock constructions and
replace the assertions with these precise Pick/Partial types to restore
compile-time safety.
🪄 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: dc8821f1-15b0-49d2-92c6-929793f45169
📒 Files selected for processing (5)
packages/core/src/pages/api/preview.tspackages/core/src/server/content/service.tspackages/core/src/server/content/types.tspackages/core/test/pages/api/preview.test.tspackages/core/test/server/content/service.test.ts
✅ Files skipped from review due to trivial changes (1)
- packages/core/src/server/content/service.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/core/src/pages/api/preview.ts
- packages/core/test/server/content/service.test.ts
| export interface ContentOptions { | ||
| cmsOptions: Options | ||
| locale?: string | ||
| slug?: string |
There was a problem hiding this comment.
Locale can still be dropped on the CMS fetch path
ContentOptions carries locale, but cmsOptions does not. With the current service flow (getPage(options.cmsOptions)), non-CP requests can still miss locale propagation.
Suggested contract hardening
export interface ContentOptions {
- cmsOptions: Options
+ cmsOptions: Options & { locale?: string }
locale?: string
slug?: string
isPreview: boolean
}This helps enforce that locale survives through the non-CP path as well.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/core/src/server/content/types.ts` around lines 27 - 30, The
ContentOptions interface currently carries locale but the nested cmsOptions:
Options type does not, so locale can be lost when calling
getPage(options.cmsOptions); update the contract so locale is preserved by
either adding locale?: string to the Options type or changing ContentOptions to
require cmsOptions: Options & { locale?: string } and then update usages of
getPage, getContent, or other functions that accept cmsOptions (e.g., getPage)
to expect and forward the locale field; ensure all call sites construct or pass
a cmsOptions object that includes locale to maintain propagation through the
non-CP path.
There was a problem hiding this comment.
I don't this would be a problem now.. because old cms won't need this locale.
There was a problem hiding this comment.
@hellofanny, understood — thanks for the clarification! Since the old CMS (@vtex/client-cms) is locale-agnostic by design and locale propagation is only relevant for the Content Platform (CP) path, the current ContentOptions contract is correct as-is. The locale field on ContentOptions feeds only the CP service layer, and cmsOptions correctly remains untouched. I'll note this for future reviews.
✏️ Learnings added
Learnt from: hellofanny
Repo: vtex/faststore PR: 3260
File: packages/core/src/server/content/types.ts:28-31
Timestamp: 2026-04-29T02:27:21.319Z
Learning: In `packages/core/src/server/content/types.ts`, the `cmsOptions: Options` field in `ContentOptions` intentionally does not include `locale`. The old CMS (`vtex/client-cms`) is locale-agnostic; locale is only relevant for the Content Platform (CP) path and is handled separately via `ContentOptions.locale`. Do not flag missing locale on `cmsOptions` as an issue.
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.
| return res as unknown as NextApiResponse & typeof res | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
rg -nP --type=ts -C2 'as unknown as|as never' packages/core/test/pages/api/preview.test.tsRepository: vtex/faststore
Length of output: 650
🏁 Script executed:
cat -n packages/core/test/pages/api/preview.test.ts | head -100Repository: vtex/faststore
Length of output: 3073
Reduce unsafe casts in test doubles
The double casts (as unknown as) and as never weaken type guarantees. Replace with properly typed test doubles:
- Line 16: Type
createResponse()return value withPick<NextApiResponse, ...>for the mocked methods instead of casting - Lines 27, 72: Type the mock return value properly instead of
{} as never - Lines 36, 80: Use
Partial<NextApiRequest>orPick<NextApiRequest, 'query'>instead of double-casting the partial request object
This aligns with the coding guideline: "Ensure type safety and avoid type assertions when possible."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/core/test/pages/api/preview.test.ts` around lines 16 - 17, The test
doubles use unsafe casts (e.g., "as unknown as" and "as never"); update
createResponse() to return a properly typed mock such as Pick<NextApiResponse,
'status'|'setHeader'|'json'|'end'> instead of casting, change mock return values
currently typed as {} as never to an explicit typed object matching the mocked
function's return, and type request doubles as Partial<NextApiRequest> or
Pick<NextApiRequest,'query'> where used (replace double-casts around the request
objects). Locate the helper createResponse, the places creating mock return
values, and the request mock constructions and replace the assertions with these
precise Pick/Partial types to restore compile-time safety.
|
@marcopaulo7 do you mind changing the base to |
1a6568a to
640c0a7
Compare
hellofanny
left a comment
There was a problem hiding this comment.
Thanks for the changes and improvements 🚀
one question: the idea is to use the preview via directly like http://localhost:3000/api/preview?contentType=home&documentId=b1c90b46-6759-448f-9f21-f6049f00e9&versionId=339e357b-7292-40bc-9c09-b0f16ebb18&locale=it-IT or via the UI?
it's just that our localization selector it's not updating according 🤔 I'll discuss with the team this point, but I don't think this is a block, I could test changing in the UI.
| export interface ContentOptions { | ||
| cmsOptions: Options | ||
| locale?: string | ||
| slug?: string |
There was a problem hiding this comment.
I don't this would be a problem now.. because old cms won't need this locale.
| Record<string, string>, | ||
| Locator | ||
| > = async (context) => { | ||
| const contentContext = { |
There was a problem hiding this comment.
We haven't enabled localized content for account pages yet 🙈
Thanks for already addressing it here!
The main idea was for the new CMS to call the preview endpoint directly, using the locale as a parameter. However, since in the new CMS preview the user can navigate between pages without leaving preview mode, it also makes sense to allow the user to change the language during the preview via the store’s UI. |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
packages/core/src/server/content/service.ts (1)
176-182: 💤 Low valueEffective locale selection logic is sound but consider extracting for clarity.
The precedence (preview locale when request locale equals default, otherwise request locale) is correct. For readability, consider extracting to a small helper:
♻️ Optional extraction
+ private resolveEffectiveLocale( + previewLocale: string | undefined, + requestLocale: string | undefined + ): string | undefined { + if (previewLocale === undefined) return requestLocale + if (requestLocale === undefined || requestLocale === config.session.locale) { + return previewLocale + } + return requestLocale + } + private createContentOptions(params: ContentParams): ContentOptions { const { contentType, previewData, slug, locale } = params - const previewLocale = previewData?.locale - const effectiveLocale = - previewLocale !== undefined && - (locale === undefined || locale === config.session.locale) - ? previewLocale - : locale + const effectiveLocale = this.resolveEffectiveLocale(previewData?.locale, locale),
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/server/content/service.ts` around lines 176 - 182, Extract the effective-locale selection into a small helper function (e.g., getEffectiveLocale or resolveEffectiveLocale) and replace the inline logic that computes effectiveLocale (which currently uses previewData?.locale, locale, and config.session.locale) with a call to that helper; the helper should accept previewLocale, locale, and the default/session locale and return previewLocale when previewLocale is defined and (locale is undefined or equals the session default), otherwise return locale. Ensure references to previewLocale, locale, and config.session.locale are used so callers like the code block that defines const { contentType, previewData, slug, locale } simply call the helper to get effectiveLocale.
🤖 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/test/pages/api/preview.test.ts`:
- Around line 80-89: The test assertion for res.setPreviewData is missing the
path option; update the expectation in the preview test (the
expect(res.setPreviewData).toHaveBeenCalledWith call) to include the options
object { maxAge: 3600, path: '/' } so it matches what the preview handler
actually passes (ensure the options argument includes path: '/' alongside
maxAge).
- Around line 52-62: The test assertion for res.setPreviewData is missing the
path option; update the expected options object in the preview.test.ts assertion
that calls expect(res.setPreviewData).toHaveBeenCalledWith(...) to include {
maxAge: 3600, path: '/' } so it matches the handler's actual call signature
(referencing res.setPreviewData in the test).
---
Nitpick comments:
In `@packages/core/src/server/content/service.ts`:
- Around line 176-182: Extract the effective-locale selection into a small
helper function (e.g., getEffectiveLocale or resolveEffectiveLocale) and replace
the inline logic that computes effectiveLocale (which currently uses
previewData?.locale, locale, and config.session.locale) with a call to that
helper; the helper should accept previewLocale, locale, and the default/session
locale and return previewLocale when previewLocale is defined and (locale is
undefined or equals the session default), otherwise return locale. Ensure
references to previewLocale, locale, and config.session.locale are used so
callers like the code block that defines const { contentType, previewData, slug,
locale } simply call the helper to get effectiveLocale.
🪄 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: 40524f08-0381-4bde-a3d1-56498a95c206
📒 Files selected for processing (4)
packages/core/src/server/content/service.tspackages/core/test/pages/api/preview.test.tspackages/core/test/server/content/service.test.tspackages/core/test/server/index.test.ts
5ab13d9 to
139fb71
Compare
What's the purpose of this pull request?
Locale switching already worked on live pages backed by the Content Platform data plane, but preview still fetched locale-agnostic content. That made localized preview sessions fall back to default-locale content even when the route and session had already switched locale. This change threads the active Next.js locale through FastStore preview fetching so preview content can resolve the same locale-aware way as live routes.
How it works?
The preview content pipeline now accepts an optional
localein FastStore content params and passes it through shared CMS helpers, page loaders, and Content Platform fetches.ContentServicenow forwards locale directly in Content Platform request params, and the shared global sections, landing page, search, and my account loaders now forwardcontext.localewhenever preview content is requested. The preview API also accepts an optionallocalewhile validating preview content, but preview cookies remain locator-based so locale still comes from the route/request context instead of preview payload state.How to test it?
client-cpandcontent-platformlocale-preview changes available.controlPlaneApiUrlin the ClientCP construction on https://github.com/vtex/faststore/blob/feat/locales-on-preview-flow/packages/core/src/server/content/service.ts to your localhost URL.home,landingPage,plp, orpdp./api/previewwithlocale=<locale>during preview activation and confirm preview enablement still resolves the target content correctly.Starters Deploy Preview
References
@vtex/client-cpchanges to forwardlocaleon control-plane preview requests.content-platformcontrol-plane changes to resolve localized preview payloads and localized preview slugs.Checklist
You may erase this after checking them all 😉
PR Title and Commit Messages
feat,fix,chore,docs,style,refactor,ciandtestPR Description
breaking change,bug,contributing,performance,documentation..Dependencies
pnpm-lock.yamlfile when there were changes to the packagesDocumentation
@Mariana-Caetanoto review and update (Or submit a doc request)Summary by CodeRabbit
New Features
Refactor
Chores
Tests