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(
let updatedPath = exportPath._ssgPath || path
let locale = exportPath._locale || commonRenderOpts.locale
if (commonRenderOpts.locale && !isAppDir) {
if (commonRenderOpts.locale) {
const localePathResult = normalizeLocalePath(path, commonRenderOpts.locales)
if (localePathResult.detectedLocale) {
......@@ -164,7 +164,7 @@ async function exportPageImpl(
if (isDynamic && page !== nonLocalizedPath) {
const normalizedPage = isAppDir ? normalizeAppPath(page) : page
params = getParams(normalizedPage, isAppDir ? path : updatedPath)
params = getParams(normalizedPage, updatedPath)
}
const { req, res } = createRequestResponseMocks({ url: updatedPath })
......
......@@ -1616,26 +1616,15 @@ export default abstract class Server<
parsedUrl.pathname = parsedMatchedPath.pathname
addRequestMeta(req, 'rewrittenPathname', invokePathnameInfo.pathname)
}
const pathnameNoBasePath = removePathPrefix(
parsedUrl.pathname,
this.nextConfig.basePath || ''
)
const normalizeResult = normalizeLocalePath(
pathnameNoBasePath,
removePathPrefix(parsedUrl.pathname, this.nextConfig.basePath || ''),
this.nextConfig.i18n?.locales
)
if (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)) {
delete parsedUrl.query[key]
......
......@@ -745,9 +745,6 @@ export async function initialize(opts: {
handleIndex,
{
invokeOutput: matchedOutput.itemPath,
...(matchedOutput.didMatchLocalePrefixedPath
? { didMatchLocalePrefixedPath: true }
: undefined),
...(matchedOutput.error
? {
invokeStatus: 500,
......
......@@ -80,7 +80,6 @@ export type FsOutput = {
locale?: string
route?: RouteDefinition
params?: Params
didMatchLocalePrefixedPath?: boolean
requestPath?: string
error?: Error
}
......@@ -94,17 +93,13 @@ type FilesystemRouteDefinition = RouteDefinition & {
const debug = setupDebug('next:router-server:filesystem')
export type FilesystemDynamicRoute = ManifestRoute & {
kind: RouteKind
/**
* The path matcher that can be used to match paths against this route.
*/
match: PatchMatcher
}
const buildFilesystemDynamicRoute = (
page: string,
kind: RouteKind
): FilesystemDynamicRoute => {
const buildFilesystemDynamicRoute = (page: string): FilesystemDynamicRoute => {
const routeRegex = getNamedRouteRegex(page, {
prefixRouteKeys: true,
includePrefix: true,
......@@ -117,7 +112,6 @@ const buildFilesystemDynamicRoute = (
routeKeys: routeRegex.routeKeys,
match: getRouteMatcher(routeRegex),
page,
kind,
}
}
......@@ -402,13 +396,13 @@ export async function setupFsCheck(opts: {
)
const appDynamicRoutes: FilesystemDynamicRoute[] = []
const appDynamicRoutePathnames = new Set<string>()
const addAppDynamicRoute = (pathname: string, kind: RouteKind) => {
const addAppDynamicRoute = (pathname: string) => {
if (!isDynamicRoute(pathname) || appDynamicRoutePathnames.has(pathname)) {
return
}
appDynamicRoutePathnames.add(pathname)
appDynamicRoutes.push(buildFilesystemDynamicRoute(pathname, kind))
appDynamicRoutes.push(buildFilesystemDynamicRoute(pathname))
}
for (const key of Object.keys(pagesManifest)) {
......@@ -469,7 +463,7 @@ export async function setupFsCheck(opts: {
filename: appNormalizers.filename.normalize(appPathsManifest[page]),
appPaths,
} as FilesystemRouteDefinition)
addAppDynamicRoute(pathname, RouteKind.APP_PAGE)
addAppDynamicRoute(pathname)
}
const appRouteHandlers = Object.keys(appPathsManifest).filter((page) =>
......@@ -484,7 +478,7 @@ export async function setupFsCheck(opts: {
bundlePath: appNormalizers.bundlePath.normalize(page),
filename: appNormalizers.filename.normalize(appPathsManifest[page]),
} as FilesystemRouteDefinition)
addAppDynamicRoute(pathname, RouteKind.APP_ROUTE)
addAppDynamicRoute(pathname)
}
for (const route of routesManifest.dataRoutes) {
......@@ -507,7 +501,6 @@ export async function setupFsCheck(opts: {
: new RegExp(route.dataRouteRegex),
groups: routeRegex.groups,
}),
kind: isAPIRoute(route.page) ? RouteKind.PAGES_API : RouteKind.PAGES,
})
}
nextDataRoutes.add(route.page)
......@@ -524,19 +517,9 @@ export async function setupFsCheck(opts: {
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({
...route,
...buildFilesystemDynamicRoute(
route.page,
isAPIRoute(route.page) ? RouteKind.PAGES_API : RouteKind.PAGES
),
...buildFilesystemDynamicRoute(route.page),
})
}
......@@ -709,13 +692,10 @@ export async function setupFsCheck(opts: {
async getItem(
itemPath: string,
requestPath?: string,
preserveAppLocalePath = false
requestPath?: string
): Promise<FsOutput | null> {
const originalItemPath = itemPath
const itemKey = preserveAppLocalePath
? `app-locale:${originalItemPath}`
: originalItemPath
const itemKey = originalItemPath
const lruResult = getItemsLru?.get(itemKey)
if (lruResult !== undefined) {
......@@ -785,17 +765,12 @@ export async function setupFsCheck(opts: {
for (let [items, type] of itemsToCheck) {
let locale: string | undefined
let didMatchLocalePrefixedPath = false
let curItemPath = itemPath
let curDecodedItemPath = decodedItemPath
const isPageOrAppFile = type === 'pageFile' || type === 'appFile'
if (i18n && type === 'appFile' && preserveAppLocalePath) {
didMatchLocalePrefixedPath = Boolean(
normalizeLocalePath(itemPath, i18n.locales).detectedLocale
)
} else if (i18n) {
if (i18n) {
const localeResult = handleLocale(
itemPath,
// legacy behavior allows visiting static assets under
......@@ -1032,7 +1007,6 @@ export async function setupFsCheck(opts: {
itemPath: flatKeyCopy(curItemPath),
route,
params,
didMatchLocalePrefixedPath,
error,
}
......
......@@ -31,7 +31,6 @@ import { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-p
import { removePathPrefix } from '../../../shared/lib/router/utils/remove-path-prefix'
import { NextDataPathnameNormalizer } from '../../normalizers/request/next-data'
import { BasePathPathnameNormalizer } from '../../normalizers/request/base-path'
import { RouteKind } from '../../route-kind'
import { addRequestMeta } from '../../request-meta'
import { isRSCRequestHeader } from '../is-rsc-request'
......@@ -209,10 +208,6 @@ export function getResolveRoutes(
let domainLocale: ReturnType<typeof detectDomainLocale> | 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:
| ReturnType<typeof normalizeLocalePath>
| undefined = undefined
......@@ -257,7 +252,6 @@ export function getResolveRoutes(
!initialLocaleResult.detectedLocale &&
!initialLocaleResult.pathname.startsWith('/_next/')
) {
localePathWasInferred = true
parsedUrl.pathname = addPathPrefix(
initialLocaleResult.pathname === '/'
? `/${defaultLocale}`
......@@ -292,11 +286,7 @@ export function getResolveRoutes(
return
}
if (!invokedOutputs?.has(pathname)) {
const output = await fsChecker.getItem(
pathname,
undefined,
Boolean(config.i18n && !localePathWasInferred)
)
const output = await fsChecker.getItem(pathname)
if (output) {
if (
......@@ -328,16 +318,7 @@ export function getResolveRoutes(
if (invokedOutputs?.has(route.page)) {
continue
}
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)
const params = route.match(localeResult.pathname)
if (params) {
const pageOutput = await fsChecker.getItem(
......@@ -345,6 +326,14 @@ export function getResolveRoutes(
curPathname || undefined
)
// i18n locales aren't matched for app dir
if (
pageOutput?.type === 'appFile' &&
initialLocaleResult?.detectedLocale
) {
continue
}
if (pageOutput && curPathname?.startsWith('/_next/data')) {
setIsNextDataRequest()
}
......@@ -356,8 +345,6 @@ export function getResolveRoutes(
// The dynamic-route scan matched the concrete request path;
// keep those params with the fsChecker route definition.
params,
didMatchLocalePrefixedPath:
isAppRoute && routePathname !== localeResult.pathname,
}
: null
}
......@@ -515,11 +502,7 @@ export function getResolveRoutes(
if (invokedOutputs?.has(pathname) || checkLocaleApi(pathname)) {
return
}
const output = await fsChecker.getItem(
pathname,
undefined,
Boolean(config.i18n && !localePathWasInferred)
)
const output = await fsChecker.getItem(pathname)
if (
output &&
......@@ -759,7 +742,6 @@ export function getResolveRoutes(
resHeaders['x-middleware-rewrite'] = destination
parsedUrl = parseUrl(destination)
localePathWasInferred = false
if (parsedUrl.protocol) {
return {
......@@ -946,7 +928,6 @@ export function getResolveRoutes(
}
}
didRewrite = true
localePathWasInferred = false
parsedUrl.pathname = parsedDestination.pathname
Object.assign(parsedUrl.query, parsedDestination.query)
}
......
......@@ -1239,13 +1239,6 @@ async function startWatcher(
opts.fsChecker.setRouteDefinitions('pageFile', pageRouteDefinitions)
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?
serverFields.middleware = middlewareMatchers
? {
......@@ -1328,9 +1321,6 @@ async function startWatcher(
routeKeys: regex.routeKeys,
match: getRouteMatcher(regex),
page,
kind:
routeKinds.get(page) ??
(isAPIRoute(page) ? RouteKind.PAGES_API : RouteKind.PAGES),
}
}
)
......@@ -1360,9 +1350,6 @@ async function startWatcher(
: new RegExp(route.dataRouteRegex),
groups: routeRegex.groups,
}),
kind: isAPIRoute(route.page)
? RouteKind.PAGES_API
: RouteKind.PAGES,
})
}
opts.fsChecker.dynamicRoutes.unshift(...dataRoutes)
......
......@@ -201,11 +201,6 @@ export interface RequestMeta {
*/
invokePath?: string
/**
* True when an App route matched the locale-prefixed invocation pathname.
*/
didMatchLocalePrefixedPath?: boolean
/**
* The specific page output we should be matching
*/
......
......@@ -760,13 +760,8 @@ export abstract class RouteModule<
let localeResult: PathLocale | 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,
// so their pathname must remain intact for dynamic param matching.
if (i18n && isPagesRoute) {
if (i18n) {
localeResult = normalizeLocalePath(
parsedUrl.pathname || '/',
i18n.locales
......@@ -789,7 +784,7 @@ export abstract class RouteModule<
const serverUtils = getServerUtils({
page: normalizedSrcPage,
i18n: isPagesRoute ? i18n : undefined,
i18n,
basePath,
rewrites,
pageIsDynamic,
......@@ -814,7 +809,7 @@ export abstract class RouteModule<
// Ensure parsedUrl.pathname includes locale before processing
// rewrites or they won't match correctly.
if (defaultLocale && !detectedLocale && isPagesRoute) {
if (defaultLocale && !detectedLocale) {
parsedUrl.pathname = `/${defaultLocale}${parsedUrl.pathname === '/' ? '' : parsedUrl.pathname}`
}
const locale =
......@@ -831,7 +826,7 @@ export abstract class RouteModule<
// after processing rewrites we want to remove locale
// from parsedUrl pathname
if (i18n && isPagesRoute) {
if (i18n) {
parsedUrl.pathname = normalizeLocalePath(
parsedUrl.pathname || '/',
i18n.locales
......@@ -883,7 +878,10 @@ export abstract class RouteModule<
// for app router since the searchParams is populated from the
// URL so we don't want to strip the rewrite params from the URL
// so that searchParams can include them.
if (isPagesRoute) {
if (
this.definition.kind === RouteKind.PAGES ||
this.definition.kind === RouteKind.PAGES_API
) {
for (const key of [
...rewriteParamKeys,
...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 {
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(
`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