Skip to content

feat: [CP-1182] handling locales on the preview flow - #3260

Merged
hellofanny merged 6 commits into
canary-v2from
feat/locales-on-preview-flow
May 4, 2026
Merged

hellofanny merged 6 commits into
canary-v2from
feat/locales-on-preview-flow

Conversation

@marcopaulo7

@marcopaulo7 marcopaulo7 commented Apr 6, 2026 •

Copy link
Copy Markdown
Contributor

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 locale in FastStore content params and passes it through shared CMS helpers, page loaders, and Content Platform fetches. ContentService now forwards locale directly in Content Platform request params, and the shared global sections, landing page, search, and my account loaders now forward context.locale whenever preview content is requested. The preview API also accepts an optional locale while 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?

  • Start FastStore with the companion client-cp and content-platform locale-preview changes available.
  • Enable preview for localized content such as home, landingPage, plp, or pdp.
  • Open the preview page in the default locale and confirm content renders as expected.
  • Switch to another locale using the locale-prefixed route or the language selector and confirm the preview content changes to the selected locale.
  • Verify localized preview content is applied to shared global sections as well as the main page content.
  • Verify preview still works for home, landing pages, PLP, PDP, search, and the account pages that reuse global sections.
  • Call /api/preview with locale=<locale> during preview activation and confirm preview enablement still resolves the target content correctly.

Starters Deploy Preview

References

  • CP-1182
  • Companion @vtex/client-cp changes to forward locale on control-plane preview requests.
  • Companion content-platform control-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

  • 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

  • New Features

    • Locale-aware content retrieval propagated to pages, templates, and preview flows for improved multilingual rendering.
  • Refactor

    • Unified content request context to consolidate preview and locale handling across content fetches and helpers.
  • Chores

    • Updated core client dependency to a newer release.
  • Tests

    • Added tests for slug-to-parameter mapping and locale precedence/propagation in content option generation and preview handling.

@coderabbitai

coderabbitai Bot commented Apr 6, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Replaces standalone previewData with a new ContentRequestContext (bundling previewData and locale), updates types and ContentService to accept/propagate locale, updates page/server helpers and CMS helpers to pass the context into content requests, adds tests, and bumps @vtex/client-cp to 0.5.1.

Changes

Cohort / File(s) Summary
Dependency & Types
packages/core/package.json, packages/core/src/server/content/types.ts
Bumped @vtex/client-cp to 0.5.1; added ContentRequestContext; added optional locale to PreviewData; extended ContentParams/ContentOptions to include locale.
Content Service
packages/core/src/server/content/service.ts
Refactored CP client creation (single shared ClientCP); removed per-locale client creation; createContentOptions computes effectiveLocale and sets options.locale; convertOptionsToParams maps settings.seo.slug → params.slug and stops merging full filters into params.
CMS Helpers / Templates
packages/core/src/components/cms/GlobalSections.tsx, packages/core/src/components/templates/LandingPage/LandingPage.tsx
Function signatures updated to accept ContentRequestContext; calls now spread ...contentContext into contentService.getSingleContent; preview/slug conditionals reference contentContext.previewData.
Pages & Data Fetchers (SSG/SSR/Experimental)
packages/core/src/pages/..., packages/core/src/experimental/... (index, checkout, login, 404, 500, [...slug].tsx, [slug]/p.tsx, search handlers, etc.)
Many getStaticProps/getServerSideProps now destructure locale, build contentContext = { previewData, locale }, and pass it into getGlobalSectionsData and content service calls (replacing direct previewData). Signatures updated where required.
Account / Private Pages
packages/core/src/pages/pvt/account/*.tsx
Server-side props updated to construct and pass contentContext (preview + locale) into global sections fetching across account pages.
Preview API
packages/core/src/pages/api/preview.ts
Reads optional locale query param, includes it in preview session data and content lookup context; setPreviewAndRedirect extended to accept locale; content lookup calls include locale.
Tests
packages/core/test/server/content/service.test.ts, packages/core/test/pages/api/preview.test.ts, packages/core/test/server/index.test.ts
New/updated tests: slug normalization & precedence, locale selection rules for content options, preview API locale propagation; minor test imports cleanup and query-field filtering.

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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • lemagnetic
  • lucasfp13
  • hellofanny

Poem

🌍 A tiny context, two fields bright,
preview and locale set to flight.
Pages call, services hum,
slugs get tidy, locales come. ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: introducing locale handling throughout the preview flow by threading the Next.js locale through FastStore's content fetching pipeline.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/locales-on-preview-flow

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 6, 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.

@marcopaulo7 marcopaulo7 changed the title fix: Set after attribute as string instead of integer (#3245) fix: Set after attribute as string instead of integer Apr 6, 2026
@marcopaulo7
marcopaulo7 force-pushed the feat/locales-on-preview-flow branch from a2d8af3 to 3bf7514 Compare April 6, 2026 20:53
@marcopaulo7 marcopaulo7 changed the title fix: Set after attribute as string instead of integer [CP-1182] Apr 7, 2026
@marcopaulo7 marcopaulo7 changed the title [CP-1182] [CP-1182] handling locales on the preview flow Apr 7, 2026
@marcopaulo7
marcopaulo7 marked this pull request as ready for review April 7, 2026 12:51
@marcopaulo7
marcopaulo7 requested a review from a team as a code owner April 7, 2026 12:51
@marcopaulo7
marcopaulo7 requested review from lemagnetic and lucasfp13 and removed request for a team April 7, 2026 12:51
@marcopaulo7 marcopaulo7 changed the title [CP-1182] handling locales on the preview flow feat: [CP-1182] handling locales on the preview flow Apr 7, 2026
@marcopaulo7
marcopaulo7 requested a review from mateuspontes April 7, 2026 12:52

@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 (1)
packages/core/src/components/templates/LandingPage/LandingPage.tsx (1)

117-119: ⚠️ Potential issue | 🔴 Critical

Critical bug: find callback never returns a value.

The arrow function uses curly braces without a return statement, so pageBySlug will always be undefined. 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 shared contentContext helper.

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) so nested is inferred without as.

♻️ 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 Locator as the getStaticProps generic type parameter, while other pages (e.g., index.tsx, [slug]/p.tsx, [...slug].tsx) use PreviewData. For consistency across the codebase, consider using PreviewData here 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9495157 and 3bf7514.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml and included by none
📒 Files selected for processing (23)
  • packages/core/package.json
  • packages/core/src/components/cms/GlobalSections.tsx
  • packages/core/src/components/templates/LandingPage/LandingPage.tsx
  • packages/core/src/experimental/myAccountServerSideProps.ts
  • packages/core/src/experimental/searchServerSideFunctions/getServerSideProps.ts
  • packages/core/src/experimental/searchServerSideFunctions/getStaticProps.ts
  • packages/core/src/pages/404.tsx
  • packages/core/src/pages/500.tsx
  • packages/core/src/pages/[...slug].tsx
  • packages/core/src/pages/[slug]/p.tsx
  • packages/core/src/pages/api/preview.ts
  • packages/core/src/pages/checkout.tsx
  • packages/core/src/pages/index.tsx
  • packages/core/src/pages/login.tsx
  • packages/core/src/pages/pvt/account/403.tsx
  • packages/core/src/pages/pvt/account/404.tsx
  • packages/core/src/pages/pvt/account/orders/[id].tsx
  • packages/core/src/pages/pvt/account/orders/index.tsx
  • packages/core/src/pages/pvt/account/profile.tsx
  • packages/core/src/pages/pvt/account/security.tsx
  • packages/core/src/pages/pvt/account/user-details.tsx
  • packages/core/src/server/content/service.ts
  • packages/core/src/server/content/types.ts

@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

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3bf7514 and 1a84d3e.

📒 Files selected for processing (3)
  • packages/core/src/components/templates/LandingPage/LandingPage.tsx
  • packages/core/src/server/content/service.ts
  • packages/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

Comment on lines +19 to +44
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')
})
})

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 | 🟡 Minor

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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1a84d3e and 1a6568a.

📒 Files selected for processing (5)
  • packages/core/src/pages/api/preview.ts
  • packages/core/src/server/content/service.ts
  • packages/core/src/server/content/types.ts
  • packages/core/test/pages/api/preview.test.ts
  • packages/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

Comment on lines 27 to 30
export interface ContentOptions {
cmsOptions: Options
locale?: string
slug?: string

@coderabbitai coderabbitai Bot Apr 7, 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 | 🟠 Major

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.

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.

I don't this would be a problem now.. because old cms won't need this locale.

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.

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

Comment on lines +16 to +17
return res as unknown as NextApiResponse & typeof res
}

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 | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -nP --type=ts -C2 'as unknown as|as never' packages/core/test/pages/api/preview.test.ts

Repository: vtex/faststore

Length of output: 650


🏁 Script executed:

cat -n packages/core/test/pages/api/preview.test.ts | head -100

Repository: 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 with Pick<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> or Pick<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.

@hellofanny

Copy link
Copy Markdown
Contributor

@marcopaulo7 do you mind changing the base to canary-v2 instead of dev (I believe there are few similar changes there - is the branch that we are enabling the localization feature) if needed I can help with the conflicts 👍 Thank you!

@marcopaulo7
marcopaulo7 changed the base branch from dev to canary-v2 April 27, 2026 15:46
@marcopaulo7
marcopaulo7 force-pushed the feat/locales-on-preview-flow branch from 1a6568a to 640c0a7 Compare April 27, 2026 15:55

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

Thanks for the changes and improvements 🚀

Image

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.

Comment on lines 27 to 30
export interface ContentOptions {
cmsOptions: Options
locale?: string
slug?: string

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.

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 = {

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.

We haven't enabled localized content for account pages yet 🙈
Thanks for already addressing it here!

@marcopaulo7

Copy link
Copy Markdown
Contributor Author

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.

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.

@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

🧹 Nitpick comments (1)
packages/core/src/server/content/service.ts (1)

176-182: 💤 Low value

Effective 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

📥 Commits

Reviewing files that changed from the base of the PR and between 640c0a7 and 5ab13d9.

📒 Files selected for processing (4)
  • packages/core/src/server/content/service.ts
  • packages/core/test/pages/api/preview.test.ts
  • packages/core/test/server/content/service.test.ts
  • packages/core/test/server/index.test.ts

@marcopaulo7
marcopaulo7 force-pushed the feat/locales-on-preview-flow branch from 5ab13d9 to 139fb71 Compare May 4, 2026 12:38
@hellofanny
hellofanny merged commit eebd7f6 into canary-v2 May 4, 2026
4 checks passed
@hellofanny
hellofanny deleted the feat/locales-on-preview-flow branch May 4, 2026 14:25
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