Unverified Commit 52788bdf authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Revert "Fix App Router locale path matching with Pages i18n" (#98715)

Reverts vercel/next.js#98095

A stale merge of #98095 caused failures on canary:
https://github.com/vercel/next.js/actions/runs/35075051322Co-authored-by: 's avatarHendrik Liebau <mail@hendrik-liebau.de>
parent c7094123
...@@ -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 && !isAppDir) { if (commonRenderOpts.locale) {
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, isAppDir ? path : updatedPath) params = getParams(normalizedPage, updatedPath)
} }
const { req, res } = createRequestResponseMocks({ url: updatedPath }) const { req, res } = createRequestResponseMocks({ url: updatedPath })
......
...@@ -1616,26 +1616,15 @@ export default abstract class Server< ...@@ -1616,26 +1616,15 @@ 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(
pathnameNoBasePath, removePathPrefix(parsedUrl.pathname, this.nextConfig.basePath || ''),
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 parsedUrl.pathname = normalizeResult.pathname
// 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
}
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,9 +745,6 @@ export async function initialize(opts: { ...@@ -745,9 +745,6 @@ 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,7 +80,6 @@ export type FsOutput = { ...@@ -80,7 +80,6 @@ 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
} }
...@@ -94,17 +93,13 @@ type FilesystemRouteDefinition = RouteDefinition & { ...@@ -94,17 +93,13 @@ 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 = ( const buildFilesystemDynamicRoute = (page: string): FilesystemDynamicRoute => {
page: string,
kind: RouteKind
): FilesystemDynamicRoute => {
const routeRegex = getNamedRouteRegex(page, { const routeRegex = getNamedRouteRegex(page, {
prefixRouteKeys: true, prefixRouteKeys: true,
includePrefix: true, includePrefix: true,
...@@ -117,7 +112,6 @@ const buildFilesystemDynamicRoute = ( ...@@ -117,7 +112,6 @@ const buildFilesystemDynamicRoute = (
routeKeys: routeRegex.routeKeys, routeKeys: routeRegex.routeKeys,
match: getRouteMatcher(routeRegex), match: getRouteMatcher(routeRegex),
page, page,
kind,
} }
} }
...@@ -402,13 +396,13 @@ export async function setupFsCheck(opts: { ...@@ -402,13 +396,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, kind: RouteKind) => { const addAppDynamicRoute = (pathname: string) => {
if (!isDynamicRoute(pathname) || appDynamicRoutePathnames.has(pathname)) { if (!isDynamicRoute(pathname) || appDynamicRoutePathnames.has(pathname)) {
return return
} }
appDynamicRoutePathnames.add(pathname) appDynamicRoutePathnames.add(pathname)
appDynamicRoutes.push(buildFilesystemDynamicRoute(pathname, kind)) appDynamicRoutes.push(buildFilesystemDynamicRoute(pathname))
} }
for (const key of Object.keys(pagesManifest)) { for (const key of Object.keys(pagesManifest)) {
...@@ -469,7 +463,7 @@ export async function setupFsCheck(opts: { ...@@ -469,7 +463,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, RouteKind.APP_PAGE) addAppDynamicRoute(pathname)
} }
const appRouteHandlers = Object.keys(appPathsManifest).filter((page) => const appRouteHandlers = Object.keys(appPathsManifest).filter((page) =>
...@@ -484,7 +478,7 @@ export async function setupFsCheck(opts: { ...@@ -484,7 +478,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, RouteKind.APP_ROUTE) addAppDynamicRoute(pathname)
} }
for (const route of routesManifest.dataRoutes) { for (const route of routesManifest.dataRoutes) {
...@@ -507,7 +501,6 @@ export async function setupFsCheck(opts: { ...@@ -507,7 +501,6 @@ 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)
...@@ -524,19 +517,9 @@ export async function setupFsCheck(opts: { ...@@ -524,19 +517,9 @@ 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( ...buildFilesystemDynamicRoute(route.page),
route.page,
isAPIRoute(route.page) ? RouteKind.PAGES_API : RouteKind.PAGES
),
}) })
} }
...@@ -709,13 +692,10 @@ export async function setupFsCheck(opts: { ...@@ -709,13 +692,10 @@ 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 = preserveAppLocalePath const itemKey = originalItemPath
? `app-locale:${originalItemPath}`
: originalItemPath
const lruResult = getItemsLru?.get(itemKey) const lruResult = getItemsLru?.get(itemKey)
if (lruResult !== undefined) { if (lruResult !== undefined) {
...@@ -785,17 +765,12 @@ export async function setupFsCheck(opts: { ...@@ -785,17 +765,12 @@ 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 && type === 'appFile' && preserveAppLocalePath) { if (i18n) {
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
...@@ -1032,7 +1007,6 @@ export async function setupFsCheck(opts: { ...@@ -1032,7 +1007,6 @@ export async function setupFsCheck(opts: {
itemPath: flatKeyCopy(curItemPath), itemPath: flatKeyCopy(curItemPath),
route, route,
params, params,
didMatchLocalePrefixedPath,
error, error,
} }
......
...@@ -31,7 +31,6 @@ import { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-p ...@@ -31,7 +31,6 @@ 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'
...@@ -209,10 +208,6 @@ export function getResolveRoutes( ...@@ -209,10 +208,6 @@ 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
...@@ -257,7 +252,6 @@ export function getResolveRoutes( ...@@ -257,7 +252,6 @@ 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}`
...@@ -292,11 +286,7 @@ export function getResolveRoutes( ...@@ -292,11 +286,7 @@ export function getResolveRoutes(
return return
} }
if (!invokedOutputs?.has(pathname)) { if (!invokedOutputs?.has(pathname)) {
const output = await fsChecker.getItem( const output = await fsChecker.getItem(pathname)
pathname,
undefined,
Boolean(config.i18n && !localePathWasInferred)
)
if (output) { if (output) {
if ( if (
...@@ -328,16 +318,7 @@ export function getResolveRoutes( ...@@ -328,16 +318,7 @@ export function getResolveRoutes(
if (invokedOutputs?.has(route.page)) { if (invokedOutputs?.has(route.page)) {
continue continue
} }
const isAppRoute = const params = route.match(localeResult.pathname)
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(
...@@ -345,6 +326,14 @@ export function getResolveRoutes( ...@@ -345,6 +326,14 @@ 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()
} }
...@@ -356,8 +345,6 @@ export function getResolveRoutes( ...@@ -356,8 +345,6 @@ 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
} }
...@@ -515,11 +502,7 @@ export function getResolveRoutes( ...@@ -515,11 +502,7 @@ export function getResolveRoutes(
if (invokedOutputs?.has(pathname) || checkLocaleApi(pathname)) { if (invokedOutputs?.has(pathname) || checkLocaleApi(pathname)) {
return return
} }
const output = await fsChecker.getItem( const output = await fsChecker.getItem(pathname)
pathname,
undefined,
Boolean(config.i18n && !localePathWasInferred)
)
if ( if (
output && output &&
...@@ -759,7 +742,6 @@ export function getResolveRoutes( ...@@ -759,7 +742,6 @@ 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 {
...@@ -946,7 +928,6 @@ export function getResolveRoutes( ...@@ -946,7 +928,6 @@ 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,13 +1239,6 @@ async function startWatcher( ...@@ -1239,13 +1239,6 @@ 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
? { ? {
...@@ -1328,9 +1321,6 @@ async function startWatcher( ...@@ -1328,9 +1321,6 @@ 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),
} }
} }
) )
...@@ -1360,9 +1350,6 @@ async function startWatcher( ...@@ -1360,9 +1350,6 @@ 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,11 +201,6 @@ export interface RequestMeta { ...@@ -201,11 +201,6 @@ 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,13 +760,8 @@ export abstract class RouteModule< ...@@ -760,13 +760,8 @@ 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
// `i18n` is a Pages Router feature. App routes own their locale segment, if (i18n) {
// 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
...@@ -789,7 +784,7 @@ export abstract class RouteModule< ...@@ -789,7 +784,7 @@ export abstract class RouteModule<
const serverUtils = getServerUtils({ const serverUtils = getServerUtils({
page: normalizedSrcPage, page: normalizedSrcPage,
i18n: isPagesRoute ? i18n : undefined, i18n,
basePath, basePath,
rewrites, rewrites,
pageIsDynamic, pageIsDynamic,
...@@ -814,7 +809,7 @@ export abstract class RouteModule< ...@@ -814,7 +809,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 && isPagesRoute) { if (defaultLocale && !detectedLocale) {
parsedUrl.pathname = `/${defaultLocale}${parsedUrl.pathname === '/' ? '' : parsedUrl.pathname}` parsedUrl.pathname = `/${defaultLocale}${parsedUrl.pathname === '/' ? '' : parsedUrl.pathname}`
} }
const locale = const locale =
...@@ -831,7 +826,7 @@ export abstract class RouteModule< ...@@ -831,7 +826,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 && isPagesRoute) { if (i18n) {
parsedUrl.pathname = normalizeLocalePath( parsedUrl.pathname = normalizeLocalePath(
parsedUrl.pathname || '/', parsedUrl.pathname || '/',
i18n.locales i18n.locales
...@@ -883,7 +878,10 @@ export abstract class RouteModule< ...@@ -883,7 +878,10 @@ 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 (isPagesRoute) { if (
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,19 +427,6 @@ export class NextDeployInstance extends NextInstance { ...@@ -427,19 +427,6 @@ 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