Unverified Commit 42385f48 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Ensure i18n custom routes resolves correctly (#19766)

This ensures i81n custom routes are resolving correctly, it also corrects redirects for default locales when `locale: false` is not used, and this also simplifies the resolving for custom routes with i18n in `next-server` adding types for the i18n config. This also adds additional tests to prevent regression and starts leveraging a shared `NextConfig` type to allow us to share types for config values. 

Fixes: https://github.com/vercel/next.js/issues/19521
Fixes: https://github.com/vercel/next.js/issues/19403
Fixes: https://github.com/vercel/next.js/issues/19302
Fixes: https://github.com/vercel/next.js/issues/19227
parent 57e156bc
......@@ -9,6 +9,7 @@ import { warn } from './output/log'
import { ClientPagesLoaderOptions } from './webpack/loaders/next-client-pages-loader'
import { ServerlessLoaderQuery } from './webpack/loaders/next-serverless-loader'
import { LoadedEnvFiles } from '@next/env'
import { NextConfig } from '../next-server/server/config'
type PagesMapping = {
[page: string]: string
......@@ -65,7 +66,7 @@ export function createEntrypoints(
target: 'server' | 'serverless' | 'experimental-serverless-trace',
buildId: string,
previewMode: __ApiPreviewProps,
config: any,
config: NextConfig,
loadedEnvFiles: LoadedEnvFiles
): Entrypoints {
const client: WebpackEntrypoints = {}
......
......@@ -263,26 +263,6 @@ export default async function build(
) => {
const keys: any[] = []
if (r.basePath !== false && (!config.i18n || r.locale === false)) {
r.source = `${config.basePath}${r.source}`
if (r.destination && r.destination.startsWith('/')) {
r.destination = `${config.basePath}${r.destination}`
}
}
if (config.i18n && r.locale !== false) {
const basePath = r.basePath !== false ? config.basePath || '' : ''
r.source = `${basePath}/:nextInternalLocale(${config.i18n.locales
.map((locale: string) => escapeStringRegexp(locale))
.join('|')})${r.source}`
if (r.destination && r.destination?.startsWith('/')) {
r.destination = `${basePath}/:nextInternalLocale${r.destination}`
}
}
const routeRegex = pathToRegexp(r.source, keys, {
strict: true,
sensitive: false,
......@@ -322,13 +302,15 @@ export default async function build(
namedDataRouteRegex?: string
}>
i18n?: {
locales: string[]
defaultLocale: string[]
domains: Array<{
domains?: Array<{
http?: true
domain: string
locales?: string[]
defaultLocale: string
locales: string[]
}>
locales: string[]
defaultLocale: string
localeDetection?: false
}
} = {
version: 3,
......
......@@ -57,6 +57,7 @@ import WebpackConformancePlugin, {
ReactSyncScriptsConformanceCheck,
} from './webpack/plugins/webpack-conformance-plugin'
import { WellKnownErrorsPlugin } from './webpack/plugins/wellknown-errors-plugin'
import { NextConfig } from '../next-server/server/config'
type ExcludesFalse = <T>(x: T | false) => x is T
......@@ -191,7 +192,7 @@ export default async function getBaseWebpackConfig(
rewrites,
}: {
buildId: string
config: any
config: NextConfig
dev?: boolean
isServer?: boolean
pagesDir: string
......@@ -994,7 +995,7 @@ export default async function getBaseWebpackConfig(
'process.env.__NEXT_ROUTER_BASEPATH': JSON.stringify(config.basePath),
'process.env.__NEXT_HAS_REWRITES': JSON.stringify(hasRewrites),
'process.env.__NEXT_I18N_SUPPORT': JSON.stringify(!!config.i18n),
'process.env.__NEXT_I18N_DOMAINS': JSON.stringify(config.i18n.domains),
'process.env.__NEXT_I18N_DOMAINS': JSON.stringify(config.i18n?.domains),
'process.env.__NEXT_ANALYTICS_ID': JSON.stringify(config.analyticsId),
...(isServer
? {
......
......@@ -97,8 +97,7 @@ export function getUtils({
rewrite.destination,
params,
parsedUrl.query,
true,
''
true
)
Object.assign(parsedUrl.query, parsedDestination.query)
......
......@@ -88,7 +88,7 @@ export default class BuildManifestPlugin {
// omit external rewrite destinations since these aren't
// handled client-side
if (!rewrite.destination.startsWith('/')) {
delete rewrite.destination
delete (rewrite as any).destination
}
return rewrite
})
......
......@@ -32,6 +32,7 @@ import {
} from '../next-server/lib/constants'
import loadConfig, {
isTargetLikeServerless,
NextConfig,
} from '../next-server/server/config'
import { eventCliSession } from '../telemetry/events'
import { hasNextSupport } from '../telemetry/ci-info'
......@@ -132,7 +133,7 @@ interface ExportOptions {
export default async function exportApp(
dir: string,
options: ExportOptions,
configuration?: any
configuration?: NextConfig
): Promise<void> {
dir = resolve(dir)
......@@ -333,8 +334,8 @@ Read more: https://err.sh/next.js/export-image-api`
ampSkipValidation: nextConfig.experimental.amp?.skipValidation || false,
ampOptimizerConfig: nextConfig.experimental.amp?.optimizer || undefined,
locales: i18n?.locales,
locale: i18n.defaultLocale,
defaultLocale: i18n.defaultLocale,
locale: i18n?.defaultLocale,
defaultLocale: i18n?.defaultLocale,
}
const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
......@@ -499,7 +500,7 @@ Read more: https://err.sh/next.js/export-image-api`
renderError = renderError || !!result.error
if (!!result.error) errorPaths.push(path)
if (options.buildExport) {
if (options.buildExport && configuration) {
if (typeof result.fromBuildExportRevalidate !== 'undefined') {
configuration.initialPageRevalidationMap[path] =
result.fromBuildExportRevalidate
......
import * as pathToRegexp from 'next/dist/compiled/path-to-regexp'
import { parse as parseUrl } from 'url'
import { NextConfig } from '../next-server/server/config'
import * as pathToRegexp from 'next/dist/compiled/path-to-regexp'
import escapeStringRegexp from 'next/dist/compiled/escape-string-regexp'
import {
PERMANENT_REDIRECT_STATUS,
TEMPORARY_REDIRECT_STATUS,
......@@ -349,35 +351,107 @@ export interface CustomRoutes {
redirects: Redirect[]
}
async function loadRedirects(config: any) {
function processRoutes<T>(
routes: T,
config: NextConfig,
type: 'redirect' | 'rewrite' | 'header'
): T {
const _routes = (routes as any) as Array<{
source: string
locale?: false
basePath?: false
destination?: string
}>
const newRoutes: typeof _routes = []
const defaultLocales: Array<{
locale: string
base: string
}> = []
if (config.i18n && type === 'redirect') {
for (const item of config.i18n?.domains || []) {
defaultLocales.push({
locale: item.defaultLocale,
base: `http${item.http ? '' : 's'}://${item.domain}`,
})
}
defaultLocales.push({
locale: config.i18n.defaultLocale,
base: '',
})
}
for (const r of _routes) {
const srcBasePath =
config.basePath && r.basePath !== false ? config.basePath : ''
const isExternal = !r.destination?.startsWith('/')
const destBasePath = srcBasePath && !isExternal ? srcBasePath : ''
if (config.i18n && r.locale !== false) {
defaultLocales.forEach((item) => {
let destination
if (r.destination) {
destination = item.base
? `${item.base}${destBasePath}${r.destination}`
: `${destBasePath}${r.destination}`
}
newRoutes.push({
...r,
destination,
source: `${srcBasePath}/${item.locale}${r.source}`,
})
})
r.source = `/:nextInternalLocale(${config.i18n.locales
.map((locale: string) => escapeStringRegexp(locale))
.join('|')})${r.source}`
if (r.destination && r.destination?.startsWith('/')) {
r.destination = `/:nextInternalLocale${r.destination}`
}
}
r.source = `${srcBasePath}${r.source}`
if (r.destination) {
r.destination = `${destBasePath}${r.destination}`
}
newRoutes.push(r)
}
return (newRoutes as any) as T
}
async function loadRedirects(config: NextConfig) {
if (typeof config.redirects !== 'function') {
return []
}
const _redirects = await config.redirects()
checkCustomRoutes(_redirects, 'redirect')
return _redirects
let redirects = await config.redirects()
checkCustomRoutes(redirects, 'redirect')
return processRoutes(redirects, config, 'redirect')
}
async function loadRewrites(config: any) {
async function loadRewrites(config: NextConfig) {
if (typeof config.rewrites !== 'function') {
return []
}
const _rewrites = await config.rewrites()
checkCustomRoutes(_rewrites, 'rewrite')
return _rewrites
let rewrites = await config.rewrites()
checkCustomRoutes(rewrites, 'rewrite')
return processRoutes(rewrites, config, 'rewrite')
}
async function loadHeaders(config: any) {
async function loadHeaders(config: NextConfig) {
if (typeof config.headers !== 'function') {
return []
}
const _headers = await config.headers()
checkCustomRoutes(_headers, 'header')
return _headers
let headers = await config.headers()
checkCustomRoutes(headers, 'header')
return processRoutes(headers, config, 'header')
}
export default async function loadCustomRoutes(
config: any
config: NextConfig
): Promise<CustomRoutes> {
const [headers, rewrites, redirects] = await Promise.all([
loadHeaders(config),
......@@ -392,13 +466,13 @@ export default async function loadCustomRoutes(
destination: '/:file',
permanent: true,
locale: config.i18n ? false : undefined,
},
} as Redirect,
{
source: '/:notfile((?!\\.well-known(?:/.*)?)(?:[^/]+/)*[^/\\.]+)',
destination: '/:notfile/',
permanent: true,
locale: config.i18n ? false : undefined,
}
} as Redirect
)
if (config.basePath) {
redirects.unshift({
......@@ -407,7 +481,7 @@ export default async function loadCustomRoutes(
permanent: true,
basePath: false,
locale: config.i18n ? false : undefined,
})
} as Redirect)
}
} else {
redirects.unshift({
......@@ -415,7 +489,7 @@ export default async function loadCustomRoutes(
destination: '/:path+',
permanent: true,
locale: config.i18n ? false : undefined,
})
} as Redirect)
if (config.basePath) {
redirects.unshift({
source: config.basePath + '/',
......@@ -423,7 +497,7 @@ export default async function loadCustomRoutes(
permanent: true,
basePath: false,
locale: config.i18n ? false : undefined,
})
} as Redirect)
}
}
......
......@@ -738,12 +738,14 @@ export default class Router implements BaseRouter {
if (process.env.__NEXT_HAS_REWRITES) {
resolvedAs = resolveRewrites(
parseRelativeUrl(as).pathname,
addBasePath(
addLocale(delBasePath(parseRelativeUrl(as).pathname), this.locale)
),
pages,
basePath,
rewrites,
query,
(p: string) => this._resolveHref({ pathname: p }, pages).pathname!
(p: string) => this._resolveHref({ pathname: p }, pages).pathname!,
this.locales
)
if (resolvedAs !== as) {
......
......@@ -46,8 +46,7 @@ export default function prepareDestination(
destination: string,
params: Params,
query: ParsedUrlQuery,
appendParamsToQuery: boolean,
basePath: string
appendParamsToQuery: boolean
) {
let parsedDestination: {
query?: ParsedUrlQuery
......@@ -140,12 +139,8 @@ export default function prepareDestination(
}
}
const shouldAddBasePath = destination.startsWith('/') && basePath
try {
newUrl = `${shouldAddBasePath ? basePath : ''}${destinationCompiler(
params
)}`
newUrl = destinationCompiler(params)
const [pathname, hash] = newUrl.split('#')
parsedDestination.pathname = pathname
......
......@@ -3,18 +3,19 @@ import pathMatch from './path-match'
import prepareDestination from './prepare-destination'
import { Rewrite } from '../../../../lib/load-custom-routes'
import { removePathTrailingSlash } from '../../../../client/normalize-trailing-slash'
import { normalizeLocalePath } from '../../i18n/normalize-locale-path'
const customRouteMatcher = pathMatch(true)
export default function resolveRewrites(
asPath: string,
pages: string[],
basePath: string,
rewrites: Rewrite[],
query: ParsedUrlQuery,
resolveHref: (path: string) => string
resolveHref: (path: string) => string,
locales?: string[]
) {
if (!pages.includes(asPath)) {
if (!pages.includes(normalizeLocalePath(asPath, locales).pathname)) {
for (const rewrite of rewrites) {
const matcher = customRouteMatcher(rewrite.source)
const params = matcher(asPath)
......@@ -28,22 +29,28 @@ export default function resolveRewrites(
rewrite.destination,
params,
query,
true,
rewrite.basePath === false ? '' : basePath
true
)
asPath = destRes.parsedDestination.pathname!
Object.assign(query, destRes.parsedDestination.query)
if (pages.includes(removePathTrailingSlash(asPath))) {
const fsPathname = normalizeLocalePath(
removePathTrailingSlash(asPath),
locales
).pathname
if (pages.includes(fsPathname)) {
asPath = fsPathname
// check if we now match a page as this means we are done
// resolving the rewrites
break
}
// check if we match a dynamic-route, if so we break the rewrites chain
const resolvedHref = resolveHref(asPath)
const resolvedHref = resolveHref(fsPathname)
if (resolvedHref !== asPath && pages.includes(resolvedHref)) {
asPath = fsPathname
break
}
}
......
......@@ -2,15 +2,34 @@ import chalk from 'chalk'
import findUp from 'next/dist/compiled/find-up'
import os from 'os'
import { basename, extname } from 'path'
import { execOnce } from '../lib/utils'
import * as Log from '../../build/output/log'
import { CONFIG_FILE } from '../lib/constants'
import { execOnce } from '../lib/utils'
import { Header, Rewrite, Redirect } from '../../lib/load-custom-routes'
import { ImageConfig, imageConfigDefault, VALID_LOADERS } from './image-config'
const targets = ['server', 'serverless', 'experimental-serverless-trace']
const reactModes = ['legacy', 'blocking', 'concurrent']
const defaultConfig: { [key: string]: any } = {
export type NextConfig = { [key: string]: any } & {
i18n: {
domains?: Array<{
http?: true
domain: string
locales?: string[]
defaultLocale: string
}>
locales: string[]
defaultLocale: string
localeDetection?: false
} | null
headers?: () => Promise<Header[]>
rewrites?: () => Promise<Rewrite[]>
redirects?: () => Promise<Redirect[]>
}
const defaultConfig: NextConfig = {
env: [],
webpack: null,
webpackDevMiddleware: null,
......@@ -39,7 +58,7 @@ const defaultConfig: { [key: string]: any } = {
basePath: '',
sassOptions: {},
trailingSlash: false,
i18n: false,
i18n: null,
experimental: {
cpus: Math.max(
1,
......@@ -351,7 +370,7 @@ function assignDefaults(userConfig: { [key: string]: any }) {
}
if (i18n.domains) {
const invalidDomainItems = i18n.domains.filter((item: any) => {
const invalidDomainItems = i18n.domains.filter((item) => {
if (!item || typeof item !== 'object') return true
if (!item.defaultLocale) return true
if (!item.domain || typeof item.domain !== 'string') return true
......@@ -362,7 +381,7 @@ function assignDefaults(userConfig: { [key: string]: any }) {
for (const locale of item.locales) {
if (typeof locale !== 'string') hasInvalidLocale = true
for (const domainItem of i18n.domains) {
for (const domainItem of i18n.domains || []) {
if (domainItem === item) continue
if (domainItem.locales && domainItem.locales.includes(locale)) {
console.warn(
......@@ -419,7 +438,7 @@ function assignDefaults(userConfig: { [key: string]: any }) {
// make sure default Locale is at the front
i18n.locales = [
i18n.defaultLocale,
...i18n.locales.filter((locale: string) => locale !== i18n.defaultLocale),
...i18n.locales.filter((locale) => locale !== i18n.defaultLocale),
]
const localeDetectionType = typeof i18n.localeDetection
......
......@@ -49,7 +49,7 @@ import {
tryGetPreviewData,
__ApiPreviewProps,
} from './api-utils'
import loadConfig, { isTargetLikeServerless } from './config'
import loadConfig, { isTargetLikeServerless, NextConfig } from './config'
import pathMatch from '../lib/router/utils/path-match'
import { recursiveReadDirSync } from './lib/recursive-readdir-sync'
import { loadComponents, LoadComponentsReturnType } from './load-components'
......@@ -85,12 +85,9 @@ import * as Log from '../../build/output/log'
import { imageOptimizer } from './image-optimizer'
import { detectDomainLocale } from '../lib/i18n/detect-domain-locale'
import cookie from 'next/dist/compiled/cookie'
import escapeStringRegexp from 'next/dist/compiled/escape-string-regexp'
const getCustomRouteMatcher = pathMatch(true)
type NextConfig = any
type Middleware = (
req: IncomingMessage,
res: ServerResponse,
......@@ -119,7 +116,7 @@ export type ServerConstructor = {
/**
* Object what you would use in next.config.js - @default {}
*/
conf?: NextConfig
conf?: NextConfig | null
dev?: boolean
customServer?: boolean
}
......@@ -356,7 +353,6 @@ export default class Server {
pathname: localePathResult.pathname,
})
;(req as any).__nextStrippedLocale = true
parsedUrl.pathname = `${basePath || ''}${localePathResult.pathname}`
}
// If a detected locale is a domain specific locale and we aren't already
......@@ -667,38 +663,11 @@ export default class Server {
...staticFilesRoute,
]
const getCustomRouteBasePath = (r: { basePath?: false }) => {
return r.basePath !== false && this.renderOpts.dev
? this.nextConfig.basePath
: ''
}
const getCustomRouteLocalePrefix = (r: {
locale?: false
destination?: string
}) => {
const { i18n } = this.nextConfig
if (!i18n || r.locale === false || !this.renderOpts.dev) return ''
if (r.destination && r.destination.startsWith('/')) {
r.destination = `/:nextInternalLocale${r.destination}`
}
return `/:nextInternalLocale(${i18n.locales
.map((locale: string) => escapeStringRegexp(locale))
.join('|')})`
}
const getCustomRoute = (
r: Rewrite | Redirect | Header,
type: RouteType
) => {
const match = getCustomRouteMatcher(
`${getCustomRouteBasePath(r)}${getCustomRouteLocalePrefix(r)}${
r.source
}`
)
const match = getCustomRouteMatcher(r.source)
return {
...r,
......@@ -760,8 +729,7 @@ export default class Server {
redirectRoute.destination,
params,
parsedUrl.query,
false,
getCustomRouteBasePath(redirectRoute)
false
)
const { query } = parsedDestination
......@@ -801,8 +769,7 @@ export default class Server {
rewriteRoute.destination,
params,
parsedUrl.query,
true,
getCustomRouteBasePath(rewriteRoute)
true
)
// external rewrite, proxy it
......@@ -899,7 +866,7 @@ export default class Server {
dynamicRoutes: this.dynamicRoutes,
basePath: this.nextConfig.basePath,
pageChecker: this.hasPage.bind(this),
locales: this.nextConfig.i18n?.locales,
locales: this.nextConfig.i18n?.locales || [],
}
}
......@@ -1286,7 +1253,7 @@ export default class Server {
: (query.__nextDefaultLocale as string)
const { i18n } = this.nextConfig
const locales = i18n.locales as string[]
const locales = i18n?.locales
let previewData: string | false | object | undefined
let isPreviewMode = false
......
......@@ -173,37 +173,50 @@ export default class Router {
// in the pathname here to allow custom-routes to require containing
// it or not, filesystem routes and pages must always include the basePath
// if it is set
let currentPathname = parsedUrlUpdated.pathname
let currentPathname = parsedUrlUpdated.pathname as string
const originalPathname = currentPathname
const requireBasePath = testRoute.requireBasePath !== false
const isCustomRoute = customRouteTypes.has(testRoute.type)
const isPublicFolderCatchall = testRoute.name === 'public folder catchall'
const keepBasePath = isCustomRoute || isPublicFolderCatchall
const keepLocale = isCustomRoute
const currentPathnameNoBasePath = replaceBasePath(
this.basePath,
currentPathname
)
if (!keepBasePath) {
currentPathname = replaceBasePath(this.basePath, currentPathname!)
currentPathname = currentPathnameNoBasePath
}
// re-add locale for custom-routes to allow matching against
if (isCustomRoute && parsedUrl.query.__nextLocale) {
if (keepBasePath) {
currentPathname = replaceBasePath(this.basePath, currentPathname!)
const localePathResult = normalizeLocalePath(
currentPathnameNoBasePath,
this.locales
)
const activeBasePath = keepBasePath ? this.basePath : ''
if (keepLocale) {
if (!localePathResult.detectedLocale && parsedUrl.query.__nextLocale) {
currentPathname = `${activeBasePath}/${parsedUrl.query.__nextLocale}${
currentPathnameNoBasePath === '/' ? '' : currentPathnameNoBasePath
}`
}
currentPathname = `/${parsedUrl.query.__nextLocale}${
currentPathname === '/' ? '' : currentPathname
}`
if (
(req as any).__nextHadTrailingSlash &&
!currentPathname.endsWith('/')
) {
currentPathname += '/'
}
if (keepBasePath) {
currentPathname = `${this.basePath}${currentPathname}`
}
} else {
currentPathname = `${
(req as any)._nextHadBasePath ? activeBasePath : ''
}${
activeBasePath && localePathResult.pathname === '/'
? ''
: localePathResult.pathname
}`
}
const newParams = testRoute.match(currentPathname)
......
......@@ -32,6 +32,7 @@ import { ClientPagesLoaderOptions } from '../build/webpack/loaders/next-client-p
import { stringify } from 'querystring'
import { Rewrite } from '../lib/load-custom-routes'
import { difference } from '../build/utils'
import { NextConfig } from '../next-server/server/config'
export async function renderScriptError(
res: ServerResponse,
......@@ -143,7 +144,7 @@ export default class HotReloader {
private middlewares: any[]
private pagesDir: string
private webpackHotMiddleware: (NextHandleFunction & any) | null
private config: any
private config: NextConfig
private stats: webpack.Stats | null
private serverStats: webpack.Stats | null
private clientError: Error | null = null
......@@ -164,7 +165,7 @@ export default class HotReloader {
previewProps,
rewrites,
}: {
config: object
config: NextConfig
pagesDir: string
buildId: string
previewProps: __ApiPreviewProps
......
const destination = 'http://localhost:__EXTERNAL_PORT__'
module.exports = {
i18n: {
// localeDetection: false,
locales: ['nl-NL', 'nl-BE', 'nl', 'fr-BE', 'fr', 'en'],
defaultLocale: 'en',
domains: [
{
// used for testing, this should not be needed in most cases
// as production domains should always use https
http: true,
domain: 'example.be',
defaultLocale: 'nl-BE',
locales: ['nl', 'nl-NL', 'nl-BE'],
},
{
http: true,
domain: 'example.fr',
defaultLocale: 'fr',
locales: ['fr-BE'],
},
],
},
async rewrites() {
return [
{
source: '/:path*',
destination: '/:path*',
},
{
source: '/en',
destination: '/en/links',
locale: false,
},
{
source: '/nl-NL',
destination: '/nl-NL/links',
locale: false,
},
{
source: '/fr',
destination: `/fr/links`,
locale: false,
},
{
source: '/en/about',
destination: `${destination}/about`,
locale: false,
},
{
source: '/nl-NL/about',
destination: `${destination}/about`,
locale: false,
},
{
source: '/fr/about',
destination: `${destination}/fr/about`,
locale: false,
},
{
source: '/en/catch-all/:path*',
destination: `${destination}/:path*`,
locale: false,
},
{
source: '/nl-NL/catch-all/:path*',
destination: `${destination}/:path*`,
locale: false,
},
{
source: '/fr/catch-all/:path*',
destination: `${destination}/fr/:path*`,
locale: false,
},
]
},
async redirects() {
return [
{
source: '/redirect-1',
destination: '/destination-1',
permanent: false,
},
{
source: '/nl-NL/redirect-2',
destination: '/destination-2',
locale: false,
permanent: false,
},
{
source: '/redirect-3',
destination: '/another',
permanent: false,
},
]
},
}
import Link from 'next/link'
export default function Links() {
return (
<>
<p id="links">Links</p>
<Link href="/">
<a id="to-index">to /</a>
</Link>
<br />
<Link href="/about">
<a id="to-about">to /about</a>
</Link>
<br />
<Link href="/catch-all/hello">
<a id="to-catch-all">to /catch-all/hello</a>
</Link>
<br />
<Link href="/links">
<a id="to-links">to /links</a>
</Link>
</>
)
}
/* eslint-env jest */
import url from 'url'
import http from 'http'
import { join } from 'path'
import cheerio from 'cheerio'
import webdriver from 'next-webdriver'
import {
launchApp,
killApp,
findPort,
nextBuild,
nextStart,
File,
fetchViaHTTP,
check,
} from 'next-test-utils'
jest.setTimeout(1000 * 60 * 2)
const appDir = join(__dirname, '..')
const nextConfig = new File(join(appDir, 'next.config.js'))
let server
let externalPort
let appPort
let app
const runTests = () => {
it('should respond to default locale redirects correctly', async () => {
for (const [path, dest] of [
['/redirect-1', '/destination-1'],
['/en/redirect-1', '/destination-1'],
['/fr/redirect-1', 'http://example.fr/destination-1'],
['/nl-NL/redirect-2', '/destination-2'],
['/fr/redirect-2', false],
]) {
const res = await fetchViaHTTP(appPort, path, undefined, {
redirect: 'manual',
})
expect(res.status).toBe(dest ? 307 : 404)
if (dest) {
if (dest.startsWith('/')) {
const parsed = url.parse(res.headers.get('location'))
expect(parsed.pathname).toBe(dest)
expect(parsed.query).toBe(null)
} else {
expect(res.headers.get('location')).toBe(dest)
}
}
}
})
it('should rewrite index routes correctly', async () => {
for (const path of ['/', '/fr', '/nl-NL']) {
const res = await fetchViaHTTP(appPort, path, undefined, {
redirect: 'manual',
})
expect(res.status).toBe(200)
const $ = cheerio.load(await res.text())
expect($('#links').text()).toBe('Links')
}
})
it('should rewrite correctly', async () => {
for (const [path, dest] of [
['/about', '/about'],
['/en/about', '/about'],
['/nl-NL/about', '/about'],
['/fr/about', '/fr/about'],
['/en/catch-all/hello', '/hello'],
['/catch-all/hello', '/hello'],
['/nl-NL/catch-all/hello', '/hello'],
['/fr/catch-all/hello', '/fr/hello'],
]) {
const res = await fetchViaHTTP(appPort, path, undefined, {
redirect: 'manual',
})
expect(res.status).toBe(200)
const $ = cheerio.load(await res.text())
expect(JSON.parse($('#data').text())).toEqual({
url: dest,
})
}
})
it('should navigate on the client with rewrites correctly', async () => {
for (const locale of ['', '/nl-NL', '/fr']) {
const browser = await webdriver(appPort, `${locale}/links`)
const expectedIndex = locale === '/fr' ? `fr` : ''
await browser.elementByCss('#to-about').click()
await check(async () => {
const data = JSON.parse(await browser.elementByCss('#data').text())
console.log(data)
return data.url === `${expectedIndex ? '/fr' : ''}/about`
? 'success'
: 'fail'
}, 'success')
await browser
.back()
.waitForElementByCss('#links')
.elementByCss('#to-catch-all')
.click()
await check(async () => {
const data = JSON.parse(await browser.elementByCss('#data').text())
console.log(data)
return data.url === `${expectedIndex ? '/fr' : ''}/hello`
? 'success'
: 'fail'
}, 'success')
await browser.back().waitForElementByCss('#links')
await browser.eval('window.beforeNav = 1')
await browser.elementByCss('#to-index').click()
await check(() => browser.eval('window.location.pathname'), locale || '/')
expect(await browser.eval('window.beforeNav')).toBe(1)
await browser.elementByCss('#to-links').click()
await check(
() => browser.eval('window.location.pathname'),
`${locale}/links`
)
expect(await browser.eval('window.beforeNav')).toBe(1)
}
})
}
describe('Custom routes i18n', () => {
beforeAll(async () => {
externalPort = await findPort()
server = http.createServer((req, res) => {
res.statusCode = 200
res.end(
`<p id='data'>${JSON.stringify({
url: req.url,
})}</p>`
)
})
await new Promise((res, rej) => {
server.listen(externalPort, (err) => (err ? rej(err) : res()))
})
nextConfig.replace(/__EXTERNAL_PORT__/g, '' + externalPort)
})
afterAll(async () => {
server.close()
nextConfig.restore()
})
describe('dev mode', () => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort)
})
afterAll(() => killApp(app))
runTests(true)
})
describe('production mode', () => {
beforeAll(async () => {
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
runTests()
})
})
......@@ -412,7 +412,7 @@ export function runTests(ctx) {
['/en/redirect-1', false],
['/nl/redirect-2', true],
['/fr/redirect-2', false],
['/redirect-3', true, '/en-US'],
['/redirect-3', true],
['/en/redirect-3', true, '/en'],
['/nl-NL/redirect-3', true, '/nl-NL'],
]) {
......
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