Unverified Commit 7c5089fe authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

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

Reverts vercel/next.js#98715. Re-apply the i18n fix.

---------
Co-authored-by: 's avatarTim Neutkens <6324199+timneutkens@users.noreply.github.com>
parent a0e2b5dc
...@@ -149,7 +149,7 @@ async function exportPageImpl( ...@@ -149,7 +149,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) {
......
...@@ -1679,15 +1679,26 @@ export default abstract class Server< ...@@ -1679,15 +1679,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)
} }
parsedUrl.pathname = normalizeResult.pathname // 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
}
for (const key of Object.keys(parsedUrl.query)) { for (const key of Object.keys(parsedUrl.query)) {
delete parsedUrl.query[key] delete parsedUrl.query[key]
......
...@@ -816,6 +816,9 @@ export async function initialize(opts: { ...@@ -816,6 +816,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
),
}) })
} }
...@@ -693,10 +710,13 @@ export async function setupFsCheck(opts: { ...@@ -693,10 +710,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) {
...@@ -766,12 +786,17 @@ export async function setupFsCheck(opts: { ...@@ -766,12 +786,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
...@@ -1008,6 +1033,7 @@ export async function setupFsCheck(opts: { ...@@ -1008,6 +1033,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'
...@@ -210,6 +211,10 @@ export function getResolveRoutes( ...@@ -210,6 +211,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
...@@ -251,6 +256,7 @@ export function getResolveRoutes( ...@@ -251,6 +256,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}`
...@@ -285,7 +291,11 @@ export function getResolveRoutes( ...@@ -285,7 +291,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 (
...@@ -317,22 +327,24 @@ export function getResolveRoutes( ...@@ -317,22 +327,24 @@ 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(
addPathPrefix(route.page, config.basePath || ''), addPathPrefix(route.page, config.basePath || ''),
curPathname || undefined curPathname || undefined,
isAppRoute && !localePathWasInferred
) )
// 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()
} }
...@@ -344,6 +356,8 @@ export function getResolveRoutes( ...@@ -344,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
} }
...@@ -501,7 +515,11 @@ export function getResolveRoutes( ...@@ -501,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 &&
...@@ -607,6 +625,7 @@ export function getResolveRoutes( ...@@ -607,6 +625,7 @@ export function getResolveRoutes(
debug('invoking middleware', req.url, req.headers) debug('invoking middleware', req.url, req.headers)
let middlewareRes: Response | undefined = undefined let middlewareRes: Response | undefined = undefined
let rewriteLocaleWasInferred = false
let bodyStream: ReadableStream | undefined = undefined let bodyStream: ReadableStream | undefined = undefined
try { try {
try { try {
...@@ -616,6 +635,8 @@ export function getResolveRoutes( ...@@ -616,6 +635,8 @@ export function getResolveRoutes(
throw err throw err
} }
middlewareRes = err.result.response as Response middlewareRes = err.result.response as Response
rewriteLocaleWasInferred =
err.result.rewriteLocaleWasInferred === true
res.statusCode = middlewareRes.status res.statusCode = middlewareRes.status
if (middlewareRes.body) { if (middlewareRes.body) {
...@@ -741,6 +762,7 @@ export function getResolveRoutes( ...@@ -741,6 +762,7 @@ export function getResolveRoutes(
resHeaders['x-middleware-rewrite'] = destination resHeaders['x-middleware-rewrite'] = destination
parsedUrl = parseUrl(destination) parsedUrl = parseUrl(destination)
localePathWasInferred = rewriteLocaleWasInferred
if (parsedUrl.protocol) { if (parsedUrl.protocol) {
return { return {
...@@ -925,6 +947,18 @@ export function getResolveRoutes( ...@@ -925,6 +947,18 @@ export function getResolveRoutes(
if (curLocaleResult.detectedLocale) { if (curLocaleResult.detectedLocale) {
addRequestMeta(req, 'locale', curLocaleResult.detectedLocale) addRequestMeta(req, 'locale', curLocaleResult.detectedLocale)
} }
// Generated i18n rewrites propagate the internal locale prefix.
// That prefix remains inferred unless the destination supplies
// an explicit locale instead.
localePathWasInferred = Boolean(
localePathWasInferred &&
route.destination.startsWith(
`${config.basePath || ''}/:nextInternalLocale`
) &&
rewriteParams.nextInternalLocale ===
curLocaleResult.detectedLocale
)
} }
didRewrite = true didRewrite = true
parsedUrl.pathname = parsedDestination.pathname parsedUrl.pathname = parsedDestination.pathname
......
...@@ -1235,6 +1235,13 @@ async function startWatcher( ...@@ -1235,6 +1235,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
? { ? {
...@@ -1317,6 +1324,9 @@ async function startWatcher( ...@@ -1317,6 +1324,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),
} }
} }
) )
...@@ -1346,6 +1356,9 @@ async function startWatcher( ...@@ -1346,6 +1356,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)
......
...@@ -198,6 +198,11 @@ export interface RequestMeta { ...@@ -198,6 +198,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
*/ */
......
...@@ -921,8 +921,13 @@ export abstract class RouteModule< ...@@ -921,8 +921,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
...@@ -945,7 +950,7 @@ export abstract class RouteModule< ...@@ -945,7 +950,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,
...@@ -970,7 +975,7 @@ export abstract class RouteModule< ...@@ -970,7 +975,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 =
...@@ -987,7 +992,7 @@ export abstract class RouteModule< ...@@ -987,7 +992,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
...@@ -1039,10 +1044,7 @@ export abstract class RouteModule< ...@@ -1039,10 +1044,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 || {}),
......
...@@ -13,6 +13,7 @@ import { ...@@ -13,6 +13,7 @@ import {
getRelativeURL, getRelativeURL,
} from '../../shared/lib/router/utils/relativize-url' } from '../../shared/lib/router/utils/relativize-url'
import { NextURL } from './next-url' import { NextURL } from './next-url'
import { getNextPathnameInfo } from '../../shared/lib/router/utils/get-next-pathname-info'
import { stripInternalSearchParams } from '../internal-utils' import { stripInternalSearchParams } from '../internal-utils'
import { normalizeRscURL } from '../../shared/lib/router/utils/app-paths' import { normalizeRscURL } from '../../shared/lib/router/utils/app-paths'
import { import {
...@@ -474,6 +475,7 @@ export async function adapter( ...@@ -474,6 +475,7 @@ export async function adapter(
* a data URL if the request was a data request. * a data URL if the request was a data request.
*/ */
const rewrite = response?.headers.get('x-middleware-rewrite') const rewrite = response?.headers.get('x-middleware-rewrite')
let rewriteLocaleWasInferred = false
if (response && rewrite && (isRSCRequest || !isEdgeRendering)) { if (response && rewrite && (isRSCRequest || !isEdgeRendering)) {
const destination = new NextURL(rewrite, { const destination = new NextURL(rewrite, {
forceLocale: true, forceLocale: true,
...@@ -484,6 +486,15 @@ export async function adapter( ...@@ -484,6 +486,15 @@ export async function adapter(
if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE && !isEdgeRendering) { if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE && !isEdgeRendering) {
if (destination.host === request.nextUrl.host) { if (destination.host === request.nextUrl.host) {
destination.buildId = buildId || destination.buildId destination.buildId = buildId || destination.buildId
// App routes must distinguish an adapter-added locale from an
// explicit locale in the Proxy's rewrite destination.
rewriteLocaleWasInferred = Boolean(
destination.locale &&
!getNextPathnameInfo(new URL(rewrite).pathname, {
nextConfig: params.request.nextConfig,
parseData: true,
}).locale
)
response.headers.set('x-middleware-rewrite', String(destination)) response.headers.set('x-middleware-rewrite', String(destination))
} }
} }
...@@ -553,6 +564,7 @@ export async function adapter( ...@@ -553,6 +564,7 @@ export async function adapter(
if (!rewriteURL.searchParams.has(NEXT_RSC_UNION_QUERY)) { if (!rewriteURL.searchParams.has(NEXT_RSC_UNION_QUERY)) {
rewriteURL.searchParams.set(NEXT_RSC_UNION_QUERY, rscHash) rewriteURL.searchParams.set(NEXT_RSC_UNION_QUERY, rscHash)
response.headers.set('x-middleware-rewrite', rewriteURL.toString()) response.headers.set('x-middleware-rewrite', rewriteURL.toString())
rewriteLocaleWasInferred = false
} }
} }
...@@ -637,5 +649,6 @@ export async function adapter( ...@@ -637,5 +649,6 @@ export async function adapter(
response: finalResponse, response: finalResponse,
waitUntil: getWaitUntilPromiseFromEvent(event) ?? Promise.resolve(), waitUntil: getWaitUntilPromiseFromEvent(event) ?? Promise.resolve(),
fetchMetrics: request.fetchMetrics, fetchMetrics: request.fetchMetrics,
rewriteLocaleWasInferred,
} }
} }
...@@ -46,6 +46,8 @@ export interface FetchEventResult { ...@@ -46,6 +46,8 @@ export interface FetchEventResult {
response: Response response: Response
waitUntil: Promise<any> waitUntil: Promise<any>
fetchMetrics?: FetchMetrics fetchMetrics?: FetchMetrics
/** Whether URL normalization added an inferred locale to a rewrite. */
rewriteLocaleWasInferred?: boolean
} }
export type NextMiddlewareResult = export type NextMiddlewareResult =
......
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>
}
export function generateStaticParams() {
return [{ id: 'value' }]
}
export default async function Page({
params,
}: {
params: Promise<{ id: string }>
}) {
const { id } = await params
return <p id="literal-locale-id">{id}</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'
import { fetchViaRawHttp } from 'next-test-utils'
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 fetchViaRawHttp(next.url, 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.each([
['en.example.local', 'en-US'],
['nl.example.local', 'nl-NL'],
])(
'routes a proxy locale rewrite to a dynamic App page on %s',
async (host, locale) => {
const response = await fetchFromDomain('/test', host)
expect(response.status).toBe(200)
expect(load(await response.text())('#app-locale').text()).toBe(locale)
}
)
it.each([
['/rewrite-plain', 'en.example.local'],
['/rewrite-plain', 'nl.example.local'],
['/rewrite-plain-clone', 'en.example.local'],
['/rewrite-plain-clone', 'nl.example.local'],
])(
'does not expose an inferred locale through proxy rewrite %s on %s',
async (pathname, host) => {
const response = await fetchFromDomain(pathname, host)
expect(response.status).toBe(200)
const $ = load(await response.text())
expect($('#plain-id').text()).toBe('123')
expect($('#app-locale').length).toBe(0)
}
)
it.each([
['en.example.local', 'en-US'],
['nl.example.local', 'nl-NL'],
])(
'preserves an explicit locale in a proxy rewrite destination on %s',
async (host, locale) => {
const response = await fetchFromDomain('/rewrite-localized', host)
expect(response.status).toBe(200)
const $ = load(await response.text())
expect($('#app-locale').text()).toBe(locale)
expect($('#app-slug').text()).toBe('plain/123')
expect($('#plain-id').length).toBe(0)
}
)
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('routes a literal locale pathname to a dynamic App page', async () => {
const response = await fetchFromDomain(
'/en-US/literal/value',
'en.example.local'
)
expect(response.status).toBe(200)
expect(load(await response.text())('#literal-locale-id').text()).toBe(
'value'
)
})
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.each(['en.example.local', 'nl.example.local'])(
'does not expose an inferred locale through a config rewrite on %s',
async (host) => {
const response = await fetchFromDomain('/old/123', host)
expect(response.status).toBe(200)
expect(load(await response.text())('#plain-id').text()).toBe('123')
}
)
it('preserves an explicit locale through a config rewrite', async () => {
const response = await fetchFromDomain('/nl-NL/old/123')
expect(response.status).toBe(200)
const $ = load(await response.text())
expect($('#app-locale').text()).toBe('nl-NL')
expect($('#app-slug').text()).toBe('plain/123')
})
it('routes an explicit config rewrite destination to a localized App page', async () => {
const response = await fetchFromDomain('/explicit/123')
expect(response.status).toBe(200)
const $ = load(await response.text())
expect($('#app-locale').text()).toBe('en-US')
expect($('#app-slug').text()).toBe('plain/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 = {
async rewrites() {
return [
{ source: '/old/:id', destination: '/plain/:id' },
{
source: '/nl-NL/explicit/:id',
destination: '/en-US/plain/:id',
locale: false,
},
]
},
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'
if (request.nextUrl.pathname === '/rewrite-plain') {
return NextResponse.rewrite(new URL('/plain/123', request.url))
}
if (request.nextUrl.pathname === '/rewrite-plain-clone') {
const url = request.nextUrl.clone()
url.pathname = '/plain/123'
return NextResponse.rewrite(url)
}
if (request.nextUrl.pathname === '/rewrite-localized') {
return NextResponse.rewrite(new URL(`/${locale}/plain/123`, request.url))
}
return NextResponse.rewrite(new URL(`/${locale}/test`, request.url))
}
export const config = {
matcher: [
'/test',
'/rewrite-plain',
'/rewrite-plain-clone',
'/rewrite-localized',
],
}
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { check, retry } from 'next-test-utils' import { check, retry } from 'next-test-utils'
import { createRouterAct } from 'router-act'
import type * as Playwright from 'playwright'
describe('parallel-routes-revalidation', () => { describe('parallel-routes-revalidation', () => {
const { next, isNextDev, isNextStart, isNextDeploy } = nextTestSetup({ const { next, isNextDev, isNextStart, isNextDeploy } = nextTestSetup({
...@@ -46,12 +44,7 @@ describe('parallel-routes-revalidation', () => { ...@@ -46,12 +44,7 @@ describe('parallel-routes-revalidation', () => {
} }
it('refreshes a retained slot using its original URL after multiple navigations', async () => { it('refreshes a retained slot using its original URL after multiple navigations', async () => {
let act: ReturnType<typeof createRouterAct> const browser = await next.browser('/prr/retained-search/one?value=first')
const browser = await next.browser('/prr/retained-search/one?value=first', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
const originalRender = await browser.elementById('retained-render').text() const originalRender = await browser.elementById('retained-render').text()
expect(await browser.elementById('retained-value').text()).toBe('first') expect(await browser.elementById('retained-value').text()).toBe('first')
...@@ -59,24 +52,24 @@ describe('parallel-routes-revalidation', () => { ...@@ -59,24 +52,24 @@ describe('parallel-routes-revalidation', () => {
['two', 'second'], ['two', 'second'],
['three', 'third'], ['three', 'third'],
]) { ]) {
await act(async () => { await browser
await browser .elementByCss(`a[href="/prr/retained-search/${page}?value=${value}"]`)
.elementByCss(`a[href="/prr/retained-search/${page}?value=${value}"]`) .click()
.click() await retry(async () => {
expect(await browser.elementById('active-page').text()).toBe(page)
}) })
expect(await browser.elementById('active-page').text()).toBe(page)
expect(await browser.elementById('retained-value').text()).toBe('first') expect(await browser.elementById('retained-value').text()).toBe('first')
expect(await browser.elementById('retained-render').text()).toBe( expect(await browser.elementById('retained-render').text()).toBe(
originalRender originalRender
) )
} }
await act(async () => { await browser.elementById('refresh-button').click()
await browser.elementById('refresh-button').click() await retry(async () => {
expect(await browser.elementById('retained-render').text()).not.toBe(
originalRender
)
}) })
expect(await browser.elementById('retained-render').text()).not.toBe(
originalRender
)
expect(await browser.elementById('retained-value').text()).toBe('first') expect(await browser.elementById('retained-value').text()).toBe('first')
expect(await browser.elementById('active-page').text()).toBe('three') expect(await browser.elementById('active-page').text()).toBe('three')
expect(new URL(await browser.url()).search).toBe('?value=third') expect(new URL(await browser.url()).search).toBe('?value=third')
...@@ -215,7 +208,11 @@ describe('parallel-routes-revalidation', () => { ...@@ -215,7 +208,11 @@ describe('parallel-routes-revalidation', () => {
// reload the page, which will cause the router to no longer have cache nodes // reload the page, which will cause the router to no longer have cache nodes
await browser.refresh() await browser.refresh()
await browser.waitForIdleNetwork() // The history listener must be hydrated before going forward. Background
// requests in development can prevent the network from becoming idle.
await retry(async () => {
expect(await browser.eval('window.__NEXT_HYDRATED')).toBe(true)
})
// go forward, this will trigger a lazy fetch for the missing data, and should restore the detail page // go forward, this will trigger a lazy fetch for the missing data, and should restore the detail page
await browser.forward() await browser.forward()
......
...@@ -667,6 +667,19 @@ export class NextDeployInstance extends NextInstance { ...@@ -667,6 +667,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