Unverified Commit 1d5dd672 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Fix App Router locale path matching with Pages i18n (#98095)

## Summary

Fix hybrid App Router and Pages Router projects using Pages i18n so
explicit or rewritten locale segments remain available to App Router
route matching, while Pages routes continue using locale-normalized
paths.

The built-in filesystem matcher now carries each route owner through
`RouteKind`, avoids duplicate App routes being treated as Pages routes
in production, and preserves literal App path parameters through the
router server, direct route-module invocation, and static export paths.
The same ownership information is maintained by the development bundler.

Adds regression coverage for domain locales, proxy rewrites, exact and
dynamic App pages, catch-all parameters, route handlers, inferred
default locales, and Pages routes. Adapter-generated routing metadata is
intentionally handled in the follow-up layers #97366 and #97500.

Closes #86048

## Verification

- `pnpm build-all`
- `NEXT_TEST_PREFER_OFFLINE=1 pnpm test-start-webpack
test/e2e/app-dir/i18n-app-pages-domain-routing/i18n-app-pages-domain-routing.test.ts`
(9 passed)
- Prettier and ESLint checks on all changed files

<!-- NEXT_JS_LLM -->
parent 65e29e4a
...@@ -140,7 +140,7 @@ async function exportPageImpl( ...@@ -140,7 +140,7 @@ async function exportPageImpl(
let updatedPath = exportPath._ssgPath || path let updatedPath = exportPath._ssgPath || path
let locale = exportPath._locale || commonRenderOpts.locale let locale = exportPath._locale || commonRenderOpts.locale
if (commonRenderOpts.locale) { if (commonRenderOpts.locale && !isAppDir) {
const localePathResult = normalizeLocalePath(path, commonRenderOpts.locales) const localePathResult = normalizeLocalePath(path, commonRenderOpts.locales)
if (localePathResult.detectedLocale) { if (localePathResult.detectedLocale) {
...@@ -164,7 +164,7 @@ async function exportPageImpl( ...@@ -164,7 +164,7 @@ async function exportPageImpl(
if (isDynamic && page !== nonLocalizedPath) { if (isDynamic && page !== nonLocalizedPath) {
const normalizedPage = isAppDir ? normalizeAppPath(page) : page const normalizedPage = isAppDir ? normalizeAppPath(page) : page
params = getParams(normalizedPage, updatedPath) params = getParams(normalizedPage, isAppDir ? path : updatedPath)
} }
const { req, res } = createRequestResponseMocks({ url: updatedPath }) const { req, res } = createRequestResponseMocks({ url: updatedPath })
......
...@@ -1616,15 +1616,26 @@ export default abstract class Server< ...@@ -1616,15 +1616,26 @@ export default abstract class Server<
parsedUrl.pathname = parsedMatchedPath.pathname parsedUrl.pathname = parsedMatchedPath.pathname
addRequestMeta(req, 'rewrittenPathname', invokePathnameInfo.pathname) addRequestMeta(req, 'rewrittenPathname', invokePathnameInfo.pathname)
} }
const pathnameNoBasePath = removePathPrefix(
parsedUrl.pathname,
this.nextConfig.basePath || ''
)
const normalizeResult = normalizeLocalePath( const normalizeResult = normalizeLocalePath(
removePathPrefix(parsedUrl.pathname, this.nextConfig.basePath || ''), pathnameNoBasePath,
this.nextConfig.i18n?.locales this.nextConfig.i18n?.locales
) )
if (normalizeResult.detectedLocale) { if (normalizeResult.detectedLocale) {
addRequestMeta(req, 'locale', normalizeResult.detectedLocale) addRequestMeta(req, 'locale', normalizeResult.detectedLocale)
} }
// The resolver already selected an App route using this literal
// pathname, so keep its locale segment for App Router param parsing.
if (getRequestMeta(req, 'didMatchLocalePrefixedPath')) {
parsedUrl.pathname = pathnameNoBasePath
removeRequestMeta(req, 'localeInferredFromDefault')
} else {
parsedUrl.pathname = normalizeResult.pathname parsedUrl.pathname = normalizeResult.pathname
}
for (const key of Object.keys(parsedUrl.query)) { for (const key of Object.keys(parsedUrl.query)) {
delete parsedUrl.query[key] delete parsedUrl.query[key]
......
...@@ -745,6 +745,9 @@ export async function initialize(opts: { ...@@ -745,6 +745,9 @@ export async function initialize(opts: {
handleIndex, handleIndex,
{ {
invokeOutput: matchedOutput.itemPath, invokeOutput: matchedOutput.itemPath,
...(matchedOutput.didMatchLocalePrefixedPath
? { didMatchLocalePrefixedPath: true }
: undefined),
...(matchedOutput.error ...(matchedOutput.error
? { ? {
invokeStatus: 500, invokeStatus: 500,
......
...@@ -80,6 +80,7 @@ export type FsOutput = { ...@@ -80,6 +80,7 @@ export type FsOutput = {
locale?: string locale?: string
route?: RouteDefinition route?: RouteDefinition
params?: Params params?: Params
didMatchLocalePrefixedPath?: boolean
requestPath?: string requestPath?: string
error?: Error error?: Error
} }
...@@ -93,13 +94,17 @@ type FilesystemRouteDefinition = RouteDefinition & { ...@@ -93,13 +94,17 @@ type FilesystemRouteDefinition = RouteDefinition & {
const debug = setupDebug('next:router-server:filesystem') const debug = setupDebug('next:router-server:filesystem')
export type FilesystemDynamicRoute = ManifestRoute & { export type FilesystemDynamicRoute = ManifestRoute & {
kind: RouteKind
/** /**
* The path matcher that can be used to match paths against this route. * The path matcher that can be used to match paths against this route.
*/ */
match: PatchMatcher match: PatchMatcher
} }
const buildFilesystemDynamicRoute = (page: string): FilesystemDynamicRoute => { const buildFilesystemDynamicRoute = (
page: string,
kind: RouteKind
): FilesystemDynamicRoute => {
const routeRegex = getNamedRouteRegex(page, { const routeRegex = getNamedRouteRegex(page, {
prefixRouteKeys: true, prefixRouteKeys: true,
includePrefix: true, includePrefix: true,
...@@ -112,6 +117,7 @@ const buildFilesystemDynamicRoute = (page: string): FilesystemDynamicRoute => { ...@@ -112,6 +117,7 @@ const buildFilesystemDynamicRoute = (page: string): FilesystemDynamicRoute => {
routeKeys: routeRegex.routeKeys, routeKeys: routeRegex.routeKeys,
match: getRouteMatcher(routeRegex), match: getRouteMatcher(routeRegex),
page, page,
kind,
} }
} }
...@@ -396,13 +402,13 @@ export async function setupFsCheck(opts: { ...@@ -396,13 +402,13 @@ export async function setupFsCheck(opts: {
) )
const appDynamicRoutes: FilesystemDynamicRoute[] = [] const appDynamicRoutes: FilesystemDynamicRoute[] = []
const appDynamicRoutePathnames = new Set<string>() const appDynamicRoutePathnames = new Set<string>()
const addAppDynamicRoute = (pathname: string) => { const addAppDynamicRoute = (pathname: string, kind: RouteKind) => {
if (!isDynamicRoute(pathname) || appDynamicRoutePathnames.has(pathname)) { if (!isDynamicRoute(pathname) || appDynamicRoutePathnames.has(pathname)) {
return return
} }
appDynamicRoutePathnames.add(pathname) appDynamicRoutePathnames.add(pathname)
appDynamicRoutes.push(buildFilesystemDynamicRoute(pathname)) appDynamicRoutes.push(buildFilesystemDynamicRoute(pathname, kind))
} }
for (const key of Object.keys(pagesManifest)) { for (const key of Object.keys(pagesManifest)) {
...@@ -463,7 +469,7 @@ export async function setupFsCheck(opts: { ...@@ -463,7 +469,7 @@ export async function setupFsCheck(opts: {
filename: appNormalizers.filename.normalize(appPathsManifest[page]), filename: appNormalizers.filename.normalize(appPathsManifest[page]),
appPaths, appPaths,
} as FilesystemRouteDefinition) } as FilesystemRouteDefinition)
addAppDynamicRoute(pathname) addAppDynamicRoute(pathname, RouteKind.APP_PAGE)
} }
const appRouteHandlers = Object.keys(appPathsManifest).filter((page) => const appRouteHandlers = Object.keys(appPathsManifest).filter((page) =>
...@@ -478,7 +484,7 @@ export async function setupFsCheck(opts: { ...@@ -478,7 +484,7 @@ export async function setupFsCheck(opts: {
bundlePath: appNormalizers.bundlePath.normalize(page), bundlePath: appNormalizers.bundlePath.normalize(page),
filename: appNormalizers.filename.normalize(appPathsManifest[page]), filename: appNormalizers.filename.normalize(appPathsManifest[page]),
} as FilesystemRouteDefinition) } as FilesystemRouteDefinition)
addAppDynamicRoute(pathname) addAppDynamicRoute(pathname, RouteKind.APP_ROUTE)
} }
for (const route of routesManifest.dataRoutes) { for (const route of routesManifest.dataRoutes) {
...@@ -501,6 +507,7 @@ export async function setupFsCheck(opts: { ...@@ -501,6 +507,7 @@ export async function setupFsCheck(opts: {
: new RegExp(route.dataRouteRegex), : new RegExp(route.dataRouteRegex),
groups: routeRegex.groups, groups: routeRegex.groups,
}), }),
kind: isAPIRoute(route.page) ? RouteKind.PAGES_API : RouteKind.PAGES,
}) })
} }
nextDataRoutes.add(route.page) nextDataRoutes.add(route.page)
...@@ -517,9 +524,19 @@ export async function setupFsCheck(opts: { ...@@ -517,9 +524,19 @@ export async function setupFsCheck(opts: {
continue continue
} }
// App routes were built from app-paths-manifest above with their
// authoritative kind. routes-manifest also contains those paths, so
// avoid registering a second copy that would be mistaken for Pages.
if (appDynamicRoutePathnames.has(route.page)) {
continue
}
filesystemDynamicRoutes.push({ filesystemDynamicRoutes.push({
...route, ...route,
...buildFilesystemDynamicRoute(route.page), ...buildFilesystemDynamicRoute(
route.page,
isAPIRoute(route.page) ? RouteKind.PAGES_API : RouteKind.PAGES
),
}) })
} }
...@@ -692,10 +709,13 @@ export async function setupFsCheck(opts: { ...@@ -692,10 +709,13 @@ export async function setupFsCheck(opts: {
async getItem( async getItem(
itemPath: string, itemPath: string,
requestPath?: string requestPath?: string,
preserveAppLocalePath = false
): Promise<FsOutput | null> { ): Promise<FsOutput | null> {
const originalItemPath = itemPath const originalItemPath = itemPath
const itemKey = originalItemPath const itemKey = preserveAppLocalePath
? `app-locale:${originalItemPath}`
: originalItemPath
const lruResult = getItemsLru?.get(itemKey) const lruResult = getItemsLru?.get(itemKey)
if (lruResult !== undefined) { if (lruResult !== undefined) {
...@@ -765,12 +785,17 @@ export async function setupFsCheck(opts: { ...@@ -765,12 +785,17 @@ export async function setupFsCheck(opts: {
for (let [items, type] of itemsToCheck) { for (let [items, type] of itemsToCheck) {
let locale: string | undefined let locale: string | undefined
let didMatchLocalePrefixedPath = false
let curItemPath = itemPath let curItemPath = itemPath
let curDecodedItemPath = decodedItemPath let curDecodedItemPath = decodedItemPath
const isPageOrAppFile = type === 'pageFile' || type === 'appFile' const isPageOrAppFile = type === 'pageFile' || type === 'appFile'
if (i18n) { if (i18n && type === 'appFile' && preserveAppLocalePath) {
didMatchLocalePrefixedPath = Boolean(
normalizeLocalePath(itemPath, i18n.locales).detectedLocale
)
} else if (i18n) {
const localeResult = handleLocale( const localeResult = handleLocale(
itemPath, itemPath,
// legacy behavior allows visiting static assets under // legacy behavior allows visiting static assets under
...@@ -1007,6 +1032,7 @@ export async function setupFsCheck(opts: { ...@@ -1007,6 +1032,7 @@ export async function setupFsCheck(opts: {
itemPath: flatKeyCopy(curItemPath), itemPath: flatKeyCopy(curItemPath),
route, route,
params, params,
didMatchLocalePrefixedPath,
error, error,
} }
......
...@@ -31,6 +31,7 @@ import { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-p ...@@ -31,6 +31,7 @@ import { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-p
import { removePathPrefix } from '../../../shared/lib/router/utils/remove-path-prefix' import { removePathPrefix } from '../../../shared/lib/router/utils/remove-path-prefix'
import { NextDataPathnameNormalizer } from '../../normalizers/request/next-data' import { NextDataPathnameNormalizer } from '../../normalizers/request/next-data'
import { BasePathPathnameNormalizer } from '../../normalizers/request/base-path' import { BasePathPathnameNormalizer } from '../../normalizers/request/base-path'
import { RouteKind } from '../../route-kind'
import { addRequestMeta } from '../../request-meta' import { addRequestMeta } from '../../request-meta'
import { isRSCRequestHeader } from '../is-rsc-request' import { isRSCRequestHeader } from '../is-rsc-request'
...@@ -208,6 +209,10 @@ export function getResolveRoutes( ...@@ -208,6 +209,10 @@ export function getResolveRoutes(
let domainLocale: ReturnType<typeof detectDomainLocale> | undefined let domainLocale: ReturnType<typeof detectDomainLocale> | undefined
let defaultLocale: string | undefined let defaultLocale: string | undefined
// The Pages Router needs an internal default-locale prefix while applying
// rewrites. App routes should only see a locale segment that was actually
// present in the request or introduced by a rewrite.
let localePathWasInferred = false
let initialLocaleResult: let initialLocaleResult:
| ReturnType<typeof normalizeLocalePath> | ReturnType<typeof normalizeLocalePath>
| undefined = undefined | undefined = undefined
...@@ -252,6 +257,7 @@ export function getResolveRoutes( ...@@ -252,6 +257,7 @@ export function getResolveRoutes(
!initialLocaleResult.detectedLocale && !initialLocaleResult.detectedLocale &&
!initialLocaleResult.pathname.startsWith('/_next/') !initialLocaleResult.pathname.startsWith('/_next/')
) { ) {
localePathWasInferred = true
parsedUrl.pathname = addPathPrefix( parsedUrl.pathname = addPathPrefix(
initialLocaleResult.pathname === '/' initialLocaleResult.pathname === '/'
? `/${defaultLocale}` ? `/${defaultLocale}`
...@@ -286,7 +292,11 @@ export function getResolveRoutes( ...@@ -286,7 +292,11 @@ export function getResolveRoutes(
return return
} }
if (!invokedOutputs?.has(pathname)) { if (!invokedOutputs?.has(pathname)) {
const output = await fsChecker.getItem(pathname) const output = await fsChecker.getItem(
pathname,
undefined,
Boolean(config.i18n && !localePathWasInferred)
)
if (output) { if (output) {
if ( if (
...@@ -318,7 +328,16 @@ export function getResolveRoutes( ...@@ -318,7 +328,16 @@ export function getResolveRoutes(
if (invokedOutputs?.has(route.page)) { if (invokedOutputs?.has(route.page)) {
continue continue
} }
const params = route.match(localeResult.pathname) const isAppRoute =
route.kind === RouteKind.APP_PAGE ||
route.kind === RouteKind.APP_ROUTE
// Pages routes match their locale-normalized pathname. App routes own
// explicit locale segments and therefore match the literal pathname.
const routePathname =
isAppRoute && !localePathWasInferred
? curPathname || '/'
: localeResult.pathname
const params = route.match(routePathname)
if (params) { if (params) {
const pageOutput = await fsChecker.getItem( const pageOutput = await fsChecker.getItem(
...@@ -326,14 +345,6 @@ export function getResolveRoutes( ...@@ -326,14 +345,6 @@ export function getResolveRoutes(
curPathname || undefined curPathname || undefined
) )
// i18n locales aren't matched for app dir
if (
pageOutput?.type === 'appFile' &&
initialLocaleResult?.detectedLocale
) {
continue
}
if (pageOutput && curPathname?.startsWith('/_next/data')) { if (pageOutput && curPathname?.startsWith('/_next/data')) {
setIsNextDataRequest() setIsNextDataRequest()
} }
...@@ -345,6 +356,8 @@ export function getResolveRoutes( ...@@ -345,6 +356,8 @@ export function getResolveRoutes(
// The dynamic-route scan matched the concrete request path; // The dynamic-route scan matched the concrete request path;
// keep those params with the fsChecker route definition. // keep those params with the fsChecker route definition.
params, params,
didMatchLocalePrefixedPath:
isAppRoute && routePathname !== localeResult.pathname,
} }
: null : null
} }
...@@ -502,7 +515,11 @@ export function getResolveRoutes( ...@@ -502,7 +515,11 @@ export function getResolveRoutes(
if (invokedOutputs?.has(pathname) || checkLocaleApi(pathname)) { if (invokedOutputs?.has(pathname) || checkLocaleApi(pathname)) {
return return
} }
const output = await fsChecker.getItem(pathname) const output = await fsChecker.getItem(
pathname,
undefined,
Boolean(config.i18n && !localePathWasInferred)
)
if ( if (
output && output &&
...@@ -742,6 +759,7 @@ export function getResolveRoutes( ...@@ -742,6 +759,7 @@ export function getResolveRoutes(
resHeaders['x-middleware-rewrite'] = destination resHeaders['x-middleware-rewrite'] = destination
parsedUrl = parseUrl(destination) parsedUrl = parseUrl(destination)
localePathWasInferred = false
if (parsedUrl.protocol) { if (parsedUrl.protocol) {
return { return {
...@@ -928,6 +946,7 @@ export function getResolveRoutes( ...@@ -928,6 +946,7 @@ export function getResolveRoutes(
} }
} }
didRewrite = true didRewrite = true
localePathWasInferred = false
parsedUrl.pathname = parsedDestination.pathname parsedUrl.pathname = parsedDestination.pathname
Object.assign(parsedUrl.query, parsedDestination.query) Object.assign(parsedUrl.query, parsedDestination.query)
} }
......
...@@ -1239,6 +1239,13 @@ async function startWatcher( ...@@ -1239,6 +1239,13 @@ async function startWatcher(
opts.fsChecker.setRouteDefinitions('pageFile', pageRouteDefinitions) opts.fsChecker.setRouteDefinitions('pageFile', pageRouteDefinitions)
opts.fsChecker.setRouteDefinitions('appFile', appRouteDefinitions) opts.fsChecker.setRouteDefinitions('appFile', appRouteDefinitions)
const routeKinds = new Map(
[...pageRouteDefinitions, ...appRouteDefinitions].map((definition) => [
definition.pathname,
definition.kind,
])
)
// TODO: pass this to fsChecker/next-dev-server? // TODO: pass this to fsChecker/next-dev-server?
serverFields.middleware = middlewareMatchers serverFields.middleware = middlewareMatchers
? { ? {
...@@ -1321,6 +1328,9 @@ async function startWatcher( ...@@ -1321,6 +1328,9 @@ async function startWatcher(
routeKeys: regex.routeKeys, routeKeys: regex.routeKeys,
match: getRouteMatcher(regex), match: getRouteMatcher(regex),
page, page,
kind:
routeKinds.get(page) ??
(isAPIRoute(page) ? RouteKind.PAGES_API : RouteKind.PAGES),
} }
} }
) )
...@@ -1350,6 +1360,9 @@ async function startWatcher( ...@@ -1350,6 +1360,9 @@ async function startWatcher(
: new RegExp(route.dataRouteRegex), : new RegExp(route.dataRouteRegex),
groups: routeRegex.groups, groups: routeRegex.groups,
}), }),
kind: isAPIRoute(route.page)
? RouteKind.PAGES_API
: RouteKind.PAGES,
}) })
} }
opts.fsChecker.dynamicRoutes.unshift(...dataRoutes) opts.fsChecker.dynamicRoutes.unshift(...dataRoutes)
......
...@@ -201,6 +201,11 @@ export interface RequestMeta { ...@@ -201,6 +201,11 @@ export interface RequestMeta {
*/ */
invokePath?: string invokePath?: string
/**
* True when an App route matched the locale-prefixed invocation pathname.
*/
didMatchLocalePrefixedPath?: boolean
/** /**
* The specific page output we should be matching * The specific page output we should be matching
*/ */
......
...@@ -760,8 +760,13 @@ export abstract class RouteModule< ...@@ -760,8 +760,13 @@ export abstract class RouteModule<
let localeResult: PathLocale | undefined let localeResult: PathLocale | undefined
let detectedLocale: string | undefined let detectedLocale: string | undefined
const isPagesRoute =
this.definition.kind === RouteKind.PAGES ||
this.definition.kind === RouteKind.PAGES_API
if (i18n) { // `i18n` is a Pages Router feature. App routes own their locale segment,
// so their pathname must remain intact for dynamic param matching.
if (i18n && isPagesRoute) {
localeResult = normalizeLocalePath( localeResult = normalizeLocalePath(
parsedUrl.pathname || '/', parsedUrl.pathname || '/',
i18n.locales i18n.locales
...@@ -784,7 +789,7 @@ export abstract class RouteModule< ...@@ -784,7 +789,7 @@ export abstract class RouteModule<
const serverUtils = getServerUtils({ const serverUtils = getServerUtils({
page: normalizedSrcPage, page: normalizedSrcPage,
i18n, i18n: isPagesRoute ? i18n : undefined,
basePath, basePath,
rewrites, rewrites,
pageIsDynamic, pageIsDynamic,
...@@ -809,7 +814,7 @@ export abstract class RouteModule< ...@@ -809,7 +814,7 @@ export abstract class RouteModule<
// Ensure parsedUrl.pathname includes locale before processing // Ensure parsedUrl.pathname includes locale before processing
// rewrites or they won't match correctly. // rewrites or they won't match correctly.
if (defaultLocale && !detectedLocale) { if (defaultLocale && !detectedLocale && isPagesRoute) {
parsedUrl.pathname = `/${defaultLocale}${parsedUrl.pathname === '/' ? '' : parsedUrl.pathname}` parsedUrl.pathname = `/${defaultLocale}${parsedUrl.pathname === '/' ? '' : parsedUrl.pathname}`
} }
const locale = const locale =
...@@ -826,7 +831,7 @@ export abstract class RouteModule< ...@@ -826,7 +831,7 @@ export abstract class RouteModule<
// after processing rewrites we want to remove locale // after processing rewrites we want to remove locale
// from parsedUrl pathname // from parsedUrl pathname
if (i18n) { if (i18n && isPagesRoute) {
parsedUrl.pathname = normalizeLocalePath( parsedUrl.pathname = normalizeLocalePath(
parsedUrl.pathname || '/', parsedUrl.pathname || '/',
i18n.locales i18n.locales
...@@ -878,10 +883,7 @@ export abstract class RouteModule< ...@@ -878,10 +883,7 @@ export abstract class RouteModule<
// for app router since the searchParams is populated from the // for app router since the searchParams is populated from the
// URL so we don't want to strip the rewrite params from the URL // URL so we don't want to strip the rewrite params from the URL
// so that searchParams can include them. // so that searchParams can include them.
if ( if (isPagesRoute) {
this.definition.kind === RouteKind.PAGES ||
this.definition.kind === RouteKind.PAGES_API
) {
for (const key of [ for (const key of [
...rewriteParamKeys, ...rewriteParamKeys,
...Object.keys(serverUtils.defaultRouteMatches || {}), ...Object.keys(serverUtils.defaultRouteMatches || {}),
......
export function generateStaticParams() {
return [
{ lang: 'nl-NL', slug: ['blog', 'post'] },
{ lang: 'en-US', slug: ['plain', 'static'] },
]
}
export default async function Page({
params,
}: {
params: Promise<{ lang: string; slug: string[] }>
}) {
const { lang, slug } = await params
return (
<>
<p id="app-locale">{lang}</p>
<p id="app-slug">{slug.join('/')}</p>
</>
)
}
import { NextResponse } from 'next/server'
export async function GET(
_request: Request,
{ params }: { params: Promise<{ lang: string }> }
) {
const { lang } = await params
return NextResponse.json({ locale: lang })
}
export function generateStaticParams() {
return [{ lang: 'en-US' }, { lang: 'nl-NL' }]
}
export default async function Page({
params,
}: {
params: Promise<{ lang: string }>
}) {
const { lang } = await params
return <p id="app-locale">{lang}</p>
}
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p id="static-app-locale">nl-NL</p>
}
export function generateStaticParams() {
return [{ id: '123' }]
}
export default async function Page({
params,
}: {
params: Promise<{ id: string }>
}) {
const { id } = await params
return <p id="plain-id">{id}</p>
}
export default function Page() {
return <p id="plain-static">plain</p>
}
import { nextTestSetup } from 'e2e-utils'
import { load } from 'cheerio'
describe('i18n-app-pages-domain-routing', () => {
const { next } = nextTestSetup({
files: __dirname,
// Adapter-generated routing metadata is covered separately. This suite
// verifies the built-in router and cannot run in deploy mode until the
// adapter-specific follow-up is applied.
skipDeployment: true,
})
function fetchFromDomain(pathname: string, host = 'nl.example.local') {
return next.fetch(pathname, {
headers: { host },
})
}
it('keeps Pages Router domain locale handling', async () => {
const response = await fetchFromDomain('/')
expect(response.status).toBe(200)
expect(load(await response.text())('#pages-locale').text()).toBe('nl-NL')
})
it('routes a proxy locale rewrite to a dynamic App page', async () => {
const response = await fetchFromDomain('/test')
expect(response.status).toBe(200)
expect(load(await response.text())('#app-locale').text()).toBe('nl-NL')
})
it('routes an explicit locale pathname to a dynamic App page', async () => {
const response = await fetchFromDomain('/en-US/test', 'en.example.local')
expect(response.status).toBe(200)
expect(load(await response.text())('#app-locale').text()).toBe('en-US')
})
it('matches App catch-all params against the locale-prefixed pathname', async () => {
const response = await fetchFromDomain('/nl-NL/blog/post')
expect(response.status).toBe(200)
const $ = load(await response.text())
expect($('#app-locale').text()).toBe('nl-NL')
expect($('#app-slug').text()).toBe('blog/post')
})
it('routes an explicit locale pathname to an exact App page', async () => {
const response = await fetchFromDomain('/nl-NL/static')
expect(response.status).toBe(200)
expect(load(await response.text())('#static-app-locale').text()).toBe(
'nl-NL'
)
})
it('does not strip an explicit locale to match an unlocalized exact App page', async () => {
const response = await fetchFromDomain(
'/en-US/plain/static',
'en.example.local'
)
expect(response.status).toBe(200)
const $ = load(await response.text())
expect($('#plain-static').length).toBe(0)
expect($('#app-locale').text()).toBe('en-US')
expect($('#app-slug').text()).toBe('plain/static')
})
it('does not expose an inferred domain locale to an unlocalized App route', async () => {
const response = await fetchFromDomain('/plain/123')
expect(response.status).toBe(200)
expect(load(await response.text())('#plain-id').text()).toBe('123')
})
it('keeps locale normalization for dynamic Pages routes', async () => {
const response = await fetchFromDomain('/nl-NL/product/widget')
expect(response.status).toBe(200)
expect(load(await response.text())('#product-locale').text()).toBe('nl-NL')
})
it('routes an explicit locale pathname to an App route handler', async () => {
const response = await fetchFromDomain('/nl-NL/endpoint')
expect(response.status).toBe(200)
expect(await response.json()).toEqual({ locale: 'nl-NL' })
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
i18n: {
locales: ['en-US', 'nl-NL'],
defaultLocale: 'en-US',
localeDetection: false,
domains: [
{
domain: 'en.example.local',
defaultLocale: 'en-US',
},
{
domain: 'nl.example.local',
defaultLocale: 'nl-NL',
},
],
},
}
module.exports = nextConfig
import { useRouter } from 'next/router'
export default function Page() {
const { locale } = useRouter()
return <p id="pages-locale">{locale}</p>
}
import { useRouter } from 'next/router'
export default function Page() {
const { locale } = useRouter()
return <p id="product-locale">{locale}</p>
}
import { NextRequest, NextResponse } from 'next/server'
const localeByHost = new Map([
['en.example.local', 'en-US'],
['nl.example.local', 'nl-NL'],
])
export function proxy(request: NextRequest) {
const hostname = request.headers.get('host')?.split(':', 1)[0] || ''
const locale = localeByHost.get(hostname) || 'en-US'
return NextResponse.rewrite(new URL(`/${locale}/test`, request.url))
}
export const config = {
matcher: '/test',
}
...@@ -427,6 +427,19 @@ export class NextDeployInstance extends NextInstance { ...@@ -427,6 +427,19 @@ export class NextDeployInstance extends NextInstance {
additionalEnv.push(`${key}=${this.env[key]}`) additionalEnv.push(`${key}=${this.env[key]}`)
} }
// Providers can expose the hostname that routes to this deployment so
// fixtures can use it in host-sensitive configuration such as
// `i18n.domains`. Vercel fixtures can use the system-provided VERCEL_URL
// instead, but forward an explicit generic hostname when one is supplied.
if (
process.env.NEXT_TEST_DEPLOYMENT_HOST &&
this.env?.NEXT_TEST_DEPLOYMENT_HOST === undefined
) {
additionalEnv.push(
`NEXT_TEST_DEPLOYMENT_HOST=${process.env.NEXT_TEST_DEPLOYMENT_HOST}`
)
}
additionalEnv.push( additionalEnv.push(
`VERCEL_CLI_VERSION=${process.env.VERCEL_CLI_VERSION || 'vercel@latest'}` `VERCEL_CLI_VERSION=${process.env.VERCEL_CLI_VERSION || 'vercel@latest'}`
) )
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment