Repository navigation
fix: i18n custom paths - SFS-3110 - #3269
Conversation
WalkthroughThis PR introduces a centralized Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~40 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 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. Review rate limit: 0/1 reviews remaining, refill in 60 minutes.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. |
5940003 to
14bf6ca
Compare
67cec7c to
2b7a9f8
Compare
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/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
📒 Files selected for processing (3)
packages/cli/src/commands/start.tspackages/cli/src/utils/generate.tspackages/core/src/proxy.ts
There was a problem hiding this comment.
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
📒 Files selected for processing (6)
packages/core/src/pages/api/fs/logout.tspackages/core/src/pages/api/graphql.tspackages/core/src/proxy.tspackages/core/src/utils/getRequestHostname.tspackages/core/src/utils/validateLocaleForHostname.tspackages/core/test/utils/getRequestHostname.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/core/src/proxy.ts
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
packages/cli/src/commands/start.tspackages/core/src/pages/api/fs/logout.tspackages/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
| return spawn( | ||
| packageManager, | ||
| ['next', 'start', tmpDir, '-p', String(port)], | ||
| { | ||
| stdio: 'inherit', | ||
| } |
There was a problem hiding this comment.
🧩 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/commandsRepository: 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.
| 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
left a comment
There was a problem hiding this comment.
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"). |
d518106 to
1b2f659
Compare
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/cli/src/commands/start.ts (1)
29-33:⚠️ Potential issue | 🟠 MajorUse
tmpDir/.nextin the build-existence guard.
next startruns fromtmpDir, but the guard still checksgetRoot()/.next. This causes unnecessary rebuilds when root artifacts exist but.faststore/.nextis 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
📒 Files selected for processing (8)
packages/cli/src/commands/start.tspackages/cli/src/utils/generate.tspackages/core/src/pages/api/fs/logout.tspackages/core/src/pages/api/graphql.tspackages/core/src/proxy.tspackages/core/src/utils/getRequestHostname.tspackages/core/src/utils/localization/validateLocaleForHostname.tspackages/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
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 withyarn dev, but failed afteryarn build && yarn startand on the standalone production deploy.Three independent issues were colliding:
faststore startwas loading the wrong Next config.next startwas being spawned without the.faststoredirectory, so Next loaded a default config from the project root withi18n = null. Withouti18n, the proxy threwTypeErroron locale rewrites.partytown copylibonly ran viapredev, so/~partytown/partytown.jswas never copied intopublic/duringbuildand the asset 404'd in production.request.nextUrl.hostnameresolves to the server bind address (0.0.0.0from theHOSTNAMEenv 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— passtmpDir(the.faststoredirectory) as a positional argument tonext start, so it loads the correctnext.config.jswith thei18nconfig derived fromdiscovery.config.js. Using a positional arg (instead of changingcwd) keepsnextresolvable from the project root via workspace hoisting.2.
packages/cli/src/utils/generate.ts— mirrorpredevwith aprebuildhook so Partytown is copied intopublic/~partytown/before the build, ensuring it ships in the standalone output.3.
packages/core/src/proxy.ts— read the hostname from theHostheader instead ofrequest.nextUrl.hostname, so binding lookup works consistently in bothnext startand standalone (node server.js) environments.shouldValidateHostnamestays enabled.How to test it?
The PR is already deployed on
brandless.fast.store, where both fixes can be verified:GET /~partytown/partytown.js→ 200 OK, confirming Partytown is shipped with the build.x-middleware-rewriteheader pointing to the locale-prefixed path (e.g./it-IT/...)./it-IT,/en-GB,/pt-BR) keep returning 200 — no regression.References
Summary by CodeRabbit
Release Notes
Refactor
Tests
Chores