Skip to content

fix: i18n custom paths - SFS-3110 - #3269

Merged
lemagnetic merged 6 commits into
canary-v2from
fix/i18n-custom-path-preview
Apr 29, 2026
Merged

lemagnetic merged 6 commits into
canary-v2from
fix/i18n-custom-path-preview

Conversation

@lemagnetic

@lemagnetic lemagnetic commented Apr 10, 2026 •

Copy link
Copy Markdown
Contributor

What's the purpose of this pull request?

Stores configured with i18n custom paths (e.g. https://store.com/europe/it) returned 404 in production whenever the URL did not match the canonical locale code (e.g. /it-IT). The same URLs worked locally with yarn dev, but failed after yarn build && yarn start and on the standalone production deploy.

Three independent issues were colliding:

  1. faststore start was loading the wrong Next config. next start was being spawned without the .faststore directory, so Next loaded a default config from the project root with i18n = null. Without i18n, the proxy threw TypeError on locale rewrites.
  2. Partytown was missing from production builds. partytown copylib only ran via predev, so /~partytown/partytown.js was never copied into public/ during build and the asset 404'd in production.
  3. Hostname validation was broken in standalone mode. request.nextUrl.hostname resolves to the server bind address (0.0.0.0 from the HOSTNAME env var set by the Dockerfile), not the client-facing host. The proxy compared this against binding hostnames (e.g. brandless.fast.store), so all binding rules were skipped and the catch-all returned 404.

How it works?

1. packages/cli/src/commands/start.ts — pass tmpDir (the .faststore directory) as a positional argument to next start, so it loads the correct next.config.js with the i18n config derived from discovery.config.js. Using a positional arg (instead of changing cwd) keeps next resolvable from the project root via workspace hoisting.

return spawn(`${packageManager} next start ${tmpDir} -p ${port}`, { ... })

2. packages/cli/src/utils/generate.ts — mirror predev with a prebuild hook so Partytown is copied into public/~partytown/ before the build, ensuring it ships in the standalone output.

predev: 'na run partytown',
prebuild: 'na run partytown',

3. packages/core/src/proxy.ts — read the hostname from the Host header instead of request.nextUrl.hostname, so binding lookup works consistently in both next start and standalone (node server.js) environments. shouldValidateHostname stays enabled.

const { pathname, search } = request.nextUrl
// In standalone, request.nextUrl.hostname is the server bind address
// (e.g. "0.0.0.0"), not the client-facing host. Use the Host header.
const hostname = request.headers.get('host')

How to test it?

The PR is already deployed on brandless.fast.store, where both fixes can be verified:

image
  • Canonical locale paths (/it-IT, /en-GB, /pt-BR) keep returning 200 — no regression.

References

Summary by CodeRabbit

Release Notes

  • Refactor

    • Centralized hostname extraction logic across API endpoints for improved consistency and reliability.
  • Tests

    • Added comprehensive test suite for hostname normalization utility covering edge cases and fallback scenarios.
  • Chores

    • Added partytown prebuild script to the build process.
    • Improved CLI start command execution with better process handling.

@coderabbitai

coderabbitai Bot commented Apr 10, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

This PR introduces a centralized getRequestHostname utility function that normalizes Host header values into lowercase hostnames with consistent port-stripping behavior. Multiple modules (proxy, logout, graphql, locale validation) are refactored to use this shared utility. CLI subprocess invocation is also updated to use tmpDir from withBasePath and spawn package manager directly with an explicit argv array.

Changes

Cohort / File(s) Summary
Hostname normalization utility
packages/core/src/utils/getRequestHostname.ts, packages/core/test/utils/getRequestHostname.test.ts
Introduces getRequestHostname helper that extracts and normalizes raw Host header values to lowercase, handles port stripping via URL parsing with fallback to colon-delimited substring, trims whitespace, and returns null for empty/missing input. Comprehensive test coverage validates edge cases (ports, localhost, whitespace, URL parsing fallback).
Core API refactoring to use shared utility
packages/core/src/proxy.ts, packages/core/src/pages/api/fs/logout.ts, packages/core/src/pages/api/graphql.ts, packages/core/src/utils/localization/validateLocaleForHostname.ts
Modules now use getRequestHostname instead of custom hostname extraction logic. Proxy applies hostname to subdomain binding and hostname validation; logout and graphql normalize cookie domains; locale validation validates hostname against bindings with early-fail for falsy hostnames.
CLI improvements
packages/cli/src/commands/start.ts, packages/cli/src/utils/generate.ts
start command derives tmpDir from withBasePath(basePath) and passes it to next start invocation. Subprocess spawning switches from shell-interpreted string (shell: true) to direct package manager executable with explicit argv array. Generated package.json adds prebuild script mirroring predev behavior.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~40 minutes

Possibly related PRs

Suggested labels

bug

Suggested reviewers

  • lariciamota
  • hellofanny
  • eduardoformiga

Poem

🎪 One hostname to rule them all,
No duplication's call,
From headers they rise,
Normalized and wise,
Consistency conquers the sprawl ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 57.14% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies a bug fix for i18n custom paths with a specific ticket reference (SFS-3110), directly matching the PR's core objective.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/i18n-custom-path-preview

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
Review rate limit: 0/1 reviews remaining, refill in 60 minutes.

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

@codesandbox-ci

codesandbox-ci Bot commented Apr 10, 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.

@lemagnetic lemagnetic changed the title fix i18n custom paths fix: i18n custom paths Apr 10, 2026
@lemagnetic
lemagnetic force-pushed the fix/i18n-custom-path-preview branch from 5940003 to 14bf6ca Compare April 13, 2026 17:21
@lemagnetic
lemagnetic force-pushed the fix/i18n-custom-path-preview branch 3 times, most recently from 67cec7c to 2b7a9f8 Compare April 28, 2026 02:25
@lemagnetic
lemagnetic marked this pull request as ready for review April 28, 2026 18:08
@lemagnetic
lemagnetic requested a review from a team as a code owner April 28, 2026 18:08
@lemagnetic
lemagnetic requested review from hellofanny and lariciamota and removed request for a team April 28, 2026 18:08

@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/cli/src/commands/start.ts`:
- Around line 39-42: The current spawn call uses a shell-interpolated command
string which breaks on paths with spaces; change the spawn invocation to call
spawn with argv array form (first arg packageManager, second arg array
['next','start', tmpDir, '-p', port]) and set shell: false and stdio: 'inherit'
so arguments are passed safely; update the same pattern in related files where
spawn is used (test.ts, dev.ts, cms-sync.ts) and reference the existing
variables packageManager, tmpDir, port and the spawn call to locate and replace
each occurrence.

In `@packages/core/src/proxy.ts`:
- Around line 100-110: Normalize the Host header before comparing bindings:
replace the current hostname = request.headers.get('host') with logic that reads
the header, falls back to request.nextUrl.hostname if missing, strips any port
(split on ':' and take the first segment), trims and lowercases the result, and
optionally removes a trailing dot; use this normalized hostname in the
binding/subdomain comparison code paths (where the variable hostname is used) so
matches aren’t missed due to ":port" or case differences.
🪄 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: 0d14615f-835f-4651-a0ec-b81a6e2b0d06

📥 Commits

Reviewing files that changed from the base of the PR and between 8ca5d06 and ad98a43.

📒 Files selected for processing (3)
  • packages/cli/src/commands/start.ts
  • packages/cli/src/utils/generate.ts
  • packages/core/src/proxy.ts

Comment thread packages/cli/src/commands/start.ts Resolved
Comment thread packages/core/src/proxy.ts Resolved

@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/test/utils/getRequestHostname.test.ts (1)

63-69: Make the fallback test assert a true fallback-only case.

This case duplicates the normal lowercase+port behavior. Consider replacing it with a malformed-host case (paired with the utility fix) so the defensive branch is actually exercised.

Suggested patch
-  describe('falls back gracefully on malformed input', () => {
-    it('returns the lowercased pre-port segment when URL parsing fails', () => {
-      // `new URL('https://...')` accepts most strings, so to exercise the
-      // fallback we rely on `.split(':')[0].toLowerCase()` for any value the
-      // URL parser cannot handle. In practice this is a defensive branch.
-      expect(getRequestHostname('STORE.COM:443')).toBe('store.com')
-    })
-  })
+  describe('falls back gracefully on malformed input', () => {
+    it('returns null when fallback hostname is empty', () => {
+      expect(getRequestHostname(':443')).toBeNull()
+    })
+  })
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/test/utils/getRequestHostname.test.ts` around lines 63 - 69,
The test currently doesn't exercise the defensive fallback in
getRequestHostname; update the test case to supply a truly malformed host string
that causes URL parsing to fail so the function uses its fallback branch (the
.split(':')[0].toLowerCase() path). Locate the test in
getRequestHostname.test.ts that calls getRequestHostname and replace the input
'STORE.COM:443' with a malformed-host example that the URL constructor rejects
(so only the fallback is used), and assert the expected lowercased pre-port
segment result from that malformed input.
🤖 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/pages/api/fs/logout.ts`:
- Around line 28-30: getRequestHostname is being forced to '' which makes
getCookieDomains produce invalid domain variants; change the logic to keep
hostname as undefined/null when unresolved and only call getCookieDomains when
hostname is truthy. Concretely, replace the current hostname assignment (const
hostname = getRequestHostname(request.headers.host) ?? '') with a plain const
hostname = getRequestHostname(request.headers.host) and then set domains =
hostname ? getCookieDomains(hostname) : [undefined] (or an empty/sentinel value)
and ensure downstream cookie-clearing code in this file only adds a domain
attribute when the domain value is defined so that unresolved hosts result in
host-only cookie clears.

In `@packages/core/src/utils/getRequestHostname.ts`:
- Around line 20-24: The catch branch in getRequestHostname currently returns
trimmed.split(':')[0].toLowerCase(), which can produce an empty string (e.g.
":443"); change the catch logic to compute the fallback host via
trimmed.split(':')[0], trim it, and if the result is an empty string return
null, otherwise return the lowercase hostname (keep the try branch returning new
URL(...).hostname.toLowerCase() as-is). Ensure this uses the same trimmed
variable and update the return path in getRequestHostname accordingly.

---

Nitpick comments:
In `@packages/core/test/utils/getRequestHostname.test.ts`:
- Around line 63-69: The test currently doesn't exercise the defensive fallback
in getRequestHostname; update the test case to supply a truly malformed host
string that causes URL parsing to fail so the function uses its fallback branch
(the .split(':')[0].toLowerCase() path). Locate the test in
getRequestHostname.test.ts that calls getRequestHostname and replace the input
'STORE.COM:443' with a malformed-host example that the URL constructor rejects
(so only the fallback is used), and assert the expected lowercased pre-port
segment result from that malformed input.
🪄 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: 12c53d8b-920b-4815-8c8b-6104e3273473

📥 Commits

Reviewing files that changed from the base of the PR and between ad98a43 and 62ef40b.

📒 Files selected for processing (6)
  • packages/core/src/pages/api/fs/logout.ts
  • packages/core/src/pages/api/graphql.ts
  • packages/core/src/proxy.ts
  • packages/core/src/utils/getRequestHostname.ts
  • packages/core/src/utils/validateLocaleForHostname.ts
  • packages/core/test/utils/getRequestHostname.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/core/src/proxy.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: 1

🤖 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/cli/src/commands/start.ts`:
- Around line 39-44: The spawn invocation currently passes tmpDir as an argument
and omits cwd, and it diverges from the project's pattern; update the call to
use the shell-style template string form used elsewhere (i.e., build a single
command string that includes packageManager and the Next start flags) and set
cwd to tmpDir, keeping stdio: 'inherit' and shell: true so the call to
spawn(packageManager/next start, ...) follows the established pattern; locate
the invocation using the spawn symbol and the packageManager, tmpDir and port
variables and replace the separate-args form with a single template command
string and an options object that includes cwd: tmpDir and shell: true.
🪄 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: 49a0c6b3-5282-43a0-8d5a-9db57a368550

📥 Commits

Reviewing files that changed from the base of the PR and between 62ef40b and d518106.

📒 Files selected for processing (3)
  • packages/cli/src/commands/start.ts
  • packages/core/src/pages/api/fs/logout.ts
  • packages/core/src/utils/getRequestHostname.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/core/src/pages/api/fs/logout.ts
  • packages/core/src/utils/getRequestHostname.ts

Comment on lines +39 to +44
return spawn(
packageManager,
['next', 'start', tmpDir, '-p', String(port)],
{
stdio: 'inherit',
}

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
set -euo pipefail

echo "== getPreferredPackageManager definition =="
fd -i "commands.ts" packages/cli/src/utils --exec sed -n '1,260p' {}

echo
echo "== CLI command call sites using getPreferredPackageManager + spawn =="
rg -nP --type=ts -C3 'getPreferredPackageManager\(|spawn\(|spawnSync\(' packages/cli/src/commands

Repository: vtex/faststore

Length of output: 8930


🏁 Script executed:

# Check if there's any documentation or usage of 'next start' with tmpDir argument
# Also check how other start commands work in the codebase
fd -i "next.*start" packages/cli/src --exec grep -n "next.*start" {}

# Check the exact context around line 39 in start.ts to understand the full picture
cat -n packages/cli/src/commands/start.ts | sed -n '25,50p'

Repository: vtex/faststore

Length of output: 796


Fix cwd binding and align spawn pattern with codebase conventions.

Line 39 omits cwd, making working directory implicit. More importantly, this spawn() pattern diverges from the rest of the codebase: line 33 (same file) and all other command invocations use spawn('${packageManager} command', { shell: true, ... }) with a template string, not separate arguments. Align this to the established pattern for consistency.

Suggested fix
    return spawn(
-     packageManager,
-     ['next', 'start', tmpDir, '-p', String(port)],
+     `${packageManager} next start ${tmpDir} -p ${port}`,
      {
+       shell: true,
+       cwd: tmpDir,
        stdio: 'inherit',
       }
    )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return spawn(
packageManager,
['next', 'start', tmpDir, '-p', String(port)],
{
stdio: 'inherit',
}
return spawn(
`${packageManager} next start ${tmpDir} -p ${port}`,
{
shell: true,
cwd: tmpDir,
stdio: 'inherit',
}
)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/cli/src/commands/start.ts` around lines 39 - 44, The spawn
invocation currently passes tmpDir as an argument and omits cwd, and it diverges
from the project's pattern; update the call to use the shell-style template
string form used elsewhere (i.e., build a single command string that includes
packageManager and the Next start flags) and set cwd to tmpDir, keeping stdio:
'inherit' and shell: true so the call to spawn(packageManager/next start, ...)
follows the established pattern; locate the invocation using the spawn symbol
and the packageManager, tmpDir and port variables and replace the separate-args
form with a single template command string and an options object that includes
cwd: tmpDir and shell: true.

@eduardoformiga eduardoformiga left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The changes LGTM!
I followed the steps to test, and it worked as mentioned 😉 .

// instead of the client-facing host, see attachRequestMeta in
// next/dist/server/next-server.js. As a result, request.nextUrl.hostname
// returns the bind address (e.g. "0.0.0.0"), which never matches the
// hostname extracted from a binding URL (e.g. "brandless.fast.store").

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

👀

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

💯

@eduardoformiga eduardoformiga changed the title fix: i18n custom paths fix: i18n custom paths - SFS-3110 Apr 28, 2026
@lemagnetic
lemagnetic force-pushed the fix/i18n-custom-path-preview branch from d518106 to 1b2f659 Compare April 29, 2026 14:20

@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 (1)
packages/cli/src/commands/start.ts (1)

29-33: ⚠️ Potential issue | 🟠 Major

Use tmpDir/.next in the build-existence guard.

next start runs from tmpDir, but the guard still checks getRoot()/.next. This causes unnecessary rebuilds when root artifacts exist but .faststore/.next is missing.

Suggested fix
-    if (!existsSync(path.join(getRoot(), '.next'))) {
+    if (!existsSync(path.join(tmpDir, '.next'))) {
       spawnSync(`${packageManager} faststore build`, {
         shell: true,
         stdio: 'inherit',
       })
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/cli/src/commands/start.ts` around lines 29 - 33, The build-existence
guard is checking for getRoot()/.next but next start runs from tmpDir, so change
the existsSync check to use the tmpDir returned by withBasePath (i.e., check
path.join(tmpDir, '.next') instead of path.join(getRoot(), '.next')) so that the
spawnSync call that runs `${packageManager} faststore build` only triggers when
the tmpDir build artifacts are missing; update any related logic in the same
block that assumes getRoot() to use tmpDir for the runtime build check.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@packages/cli/src/commands/start.ts`:
- Around line 29-33: The build-existence guard is checking for getRoot()/.next
but next start runs from tmpDir, so change the existsSync check to use the
tmpDir returned by withBasePath (i.e., check path.join(tmpDir, '.next') instead
of path.join(getRoot(), '.next')) so that the spawnSync call that runs
`${packageManager} faststore build` only triggers when the tmpDir build
artifacts are missing; update any related logic in the same block that assumes
getRoot() to use tmpDir for the runtime build check.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c93c38d7-fe28-4cb0-8841-3eb203767d7c

📥 Commits

Reviewing files that changed from the base of the PR and between d518106 and 1b2f659.

📒 Files selected for processing (8)
  • packages/cli/src/commands/start.ts
  • packages/cli/src/utils/generate.ts
  • packages/core/src/pages/api/fs/logout.ts
  • packages/core/src/pages/api/graphql.ts
  • packages/core/src/proxy.ts
  • packages/core/src/utils/getRequestHostname.ts
  • packages/core/src/utils/localization/validateLocaleForHostname.ts
  • packages/core/test/utils/getRequestHostname.test.ts
✅ Files skipped from review due to trivial changes (3)
  • packages/cli/src/utils/generate.ts
  • packages/core/src/pages/api/graphql.ts
  • packages/core/test/utils/getRequestHostname.test.ts

@lemagnetic
lemagnetic merged commit aa03da9 into canary-v2 Apr 29, 2026
3 checks passed
@lemagnetic
lemagnetic deleted the fix/i18n-custom-path-preview branch April 29, 2026 15:44
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