Unverified Commit e29bd49d authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

i18n Improvements (#47174)

This serves to correct a specific issue related to multiple locales being specified in the pathname as well as some general i18n improvements.

- Multiple locales are now parsed correctly (only taking the first locale, treating the rest of the string as the pathname)
- `LocaleRouteNormalizer` has been split into `I18NProvider` and `LocaleRouteNormalizer` (tests added)
- Adjusted the `I18NProvider.analyze` method (previously `LocaleRouteNormalizer.match`) to require the `defaultLocale: string | undefined` to ensure consistent behaviour
- Added more comments around i18n
parent 9dbd8d77
This diff is collapsed.
...@@ -322,7 +322,9 @@ export default class DevServer extends Server { ...@@ -322,7 +322,9 @@ export default class DevServer extends Server {
distDir: this.distDir, distDir: this.distDir,
buildId: this.buildId, buildId: this.buildId,
} }
) // In development we can't give a default path mapping )
// In development we can't give a default path mapping
for (const path in exportPathMap) { for (const path in exportPathMap) {
const { page, query = {} } = exportPathMap[path] const { page, query = {} } = exportPathMap[path]
...@@ -1159,6 +1161,7 @@ export default class DevServer extends Server { ...@@ -1159,6 +1161,7 @@ export default class DevServer extends Server {
const { basePath } = this.nextConfig const { basePath } = this.nextConfig
let originalPathname: string | null = null let originalPathname: string | null = null
// TODO: see if we can remove this in the future
if (basePath && pathHasPrefix(parsedUrl.pathname || '/', basePath)) { if (basePath && pathHasPrefix(parsedUrl.pathname || '/', basePath)) {
// strip basePath before handling dev bundles // strip basePath before handling dev bundles
// If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/` // If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`
...@@ -1174,15 +1177,14 @@ export default class DevServer extends Server { ...@@ -1174,15 +1177,14 @@ export default class DevServer extends Server {
} }
} }
const { finished = false } = if (this.hotReloader) {
(await this.hotReloader?.run( const { finished = false } = await this.hotReloader.run(
req.originalRequest, req.originalRequest,
res.originalResponse, res.originalResponse,
parsedUrl parsedUrl
)) || {} )
if (finished) { if (finished) return
return
} }
if (originalPathname) { if (originalPathname) {
......
import { I18NProvider } from './i18n-provider'
describe('I18NProvider', () => {
const provider = new I18NProvider({
defaultLocale: 'en',
locales: ['en', 'fr', 'en-CA'],
domains: [
{
domain: 'example.com',
defaultLocale: 'en',
locales: ['en-CA'],
},
{
domain: 'example.fr',
defaultLocale: 'fr',
},
],
})
it('should detect the correct domain locale', () => {
expect(provider.detectDomainLocale('example.com')).toEqual({
domain: 'example.com',
defaultLocale: 'en',
locales: ['en-CA'],
})
expect(provider.detectDomainLocale('example.fr')).toEqual({
domain: 'example.fr',
defaultLocale: 'fr',
})
expect(provider.detectDomainLocale('example.de')).toBeUndefined()
})
describe('analyze', () => {
it('should detect the correct default locale', () => {
expect(provider.analyze('/fr', { defaultLocale: undefined })).toEqual({
pathname: '/',
detectedLocale: 'fr',
})
expect(
provider.analyze('/fr/another/page', { defaultLocale: undefined })
).toEqual({
pathname: '/another/page',
detectedLocale: 'fr',
})
expect(
provider.analyze('/another/page', {
defaultLocale: 'en-CA',
})
).toEqual({
pathname: '/another/page',
detectedLocale: 'en-CA',
})
expect(
provider.analyze('/en/another/page', {
defaultLocale: 'en-CA',
})
).toEqual({
pathname: '/another/page',
detectedLocale: 'en',
})
})
})
})
import { DomainLocale, I18NConfig } from '../../config-shared'
/**
* The result of matching a locale aware route.
*/
interface LocaleAnalysisResult {
/**
* The pathname without the locale prefix (if any).
*/
pathname: string
/**
* The detected locale. If no locale was detected, this will be `undefined`.
*/
detectedLocale?: string
}
type LocaleAnalysisOptions = {
/**
* When provided, it will be used as the default locale if the locale
* cannot be inferred from the pathname.
*/
defaultLocale: string | undefined
}
/**
* The I18NProvider is used to match locale aware routes, detect the locale from
* the pathname and hostname and normalize the pathname by removing the locale
* prefix.
*/
export class I18NProvider {
private readonly lowerCaseLocales: ReadonlyArray<string>
private readonly lowerCaseDomains?: ReadonlyArray<
DomainLocale & {
// The configuration references a domain with an optional port, but the
// hostname is always the domain without the port and is used for
// matching.
hostname: string
}
>
constructor(public readonly config: I18NConfig) {
if (!config.locales.length) {
throw new Error('Invariant: No locales provided')
}
this.lowerCaseLocales = config.locales.map((locale) => locale.toLowerCase())
this.lowerCaseDomains = config.domains?.map((domainLocale) => {
const domain = domainLocale.domain.toLowerCase()
return {
defaultLocale: domainLocale.defaultLocale.toLowerCase(),
hostname: domain.split(':')[0],
domain,
locales: domainLocale.locales?.map((locale) => locale.toLowerCase()),
http: domainLocale.http,
}
})
}
/**
* Detects the domain locale from the hostname and the detected locale if
* provided.
*
* @param hostname The hostname to detect the domain locale from, this must be lowercased.
* @param detectedLocale The detected locale to use if the hostname does not match.
* @returns The domain locale if found, `undefined` otherwise.
*/
public detectDomainLocale(
hostname?: string,
detectedLocale?: string
): DomainLocale | undefined {
if (!hostname || !this.lowerCaseDomains || !this.config.domains) return
if (detectedLocale) detectedLocale = detectedLocale.toLowerCase()
for (let i = 0; i < this.lowerCaseDomains.length; i++) {
const domainLocale = this.lowerCaseDomains[i]
if (
// We assume that the hostname is already lowercased.
domainLocale.hostname === hostname ||
// Configuration validation ensures that the locale is not repeated in
// other domains locales.
domainLocale.locales?.some((locale) => locale === detectedLocale)
) {
return this.config.domains[i]
}
}
return
}
/**
* Analyzes the pathname for a locale and returns the pathname without it.
*
* @param pathname The pathname that could contain a locale prefix.
* @param options The options to use when matching the locale.
* @returns The matched locale and the pathname without the locale prefix
* (if any).
*/
public analyze(
pathname: string,
options: LocaleAnalysisOptions
): LocaleAnalysisResult {
let detectedLocale: string | undefined = options.defaultLocale
// The first segment will be empty, because it has a leading `/`. If
// there is no further segment, there is no locale.
const segments = pathname.split('/')
if (!segments[1]) return { detectedLocale, pathname }
// The second segment will contain the locale part if any.
const segment = segments[1].toLowerCase()
// See if the segment matches one of the locales.
const index = this.lowerCaseLocales.indexOf(segment)
if (index < 0) return { detectedLocale, pathname }
// Return the case-sensitive locale.
detectedLocale = this.config.locales[index]
// Remove the `/${locale}` part of the pathname.
pathname = pathname.slice(detectedLocale.length + 1) || '/'
return { detectedLocale, pathname }
}
}
import { I18NProvider } from '../helpers/i18n-provider'
import { Normalizer } from './normalizer' import { Normalizer } from './normalizer'
export interface LocaleRouteNormalizer extends Normalizer { /**
readonly locales: ReadonlyArray<string> * Normalizes the pathname by removing the locale prefix if any.
readonly defaultLocale: string */
match(
pathname: string,
options?: { inferDefaultLocale: boolean }
): { detectedLocale?: string; pathname: string }
}
export class LocaleRouteNormalizer implements Normalizer { export class LocaleRouteNormalizer implements Normalizer {
private readonly lowerCase: ReadonlyArray<string> constructor(private readonly provider: I18NProvider) {}
constructor( /**
public readonly locales: ReadonlyArray<string>, * Normalizes the pathname by removing the locale prefix if any.
public readonly defaultLocale: string *
) { * @param pathname The pathname to normalize.
this.lowerCase = locales.map((locale) => locale.toLowerCase()) * @returns The pathname without the locale prefix (if any).
} */
public match(
pathname: string,
options?: { inferDefaultLocale: boolean }
): {
pathname: string
detectedLocale?: string
} {
let detectedLocale: string | undefined = options?.inferDefaultLocale
? this.defaultLocale
: undefined
if (this.locales.length === 0) return { detectedLocale, pathname }
// The first segment will be empty, because it has a leading `/`. If
// there is no further segment, there is no locale.
const segments = pathname.split('/')
if (!segments[1]) return { detectedLocale, pathname }
// The second segment will contain the locale part if any.
const segment = segments[1].toLowerCase()
// See if the segment matches one of the locales.
const index = this.lowerCase.indexOf(segment)
if (index < 0) return { detectedLocale, pathname }
// Return the case-sensitive locale.
detectedLocale = this.locales[index]
// Remove the `/${locale}` part of the pathname.
pathname = pathname.slice(detectedLocale.length + 1) || '/'
return { detectedLocale, pathname }
}
public normalize(pathname: string): string { public normalize(pathname: string): string {
const match = this.match(pathname) const match = this.provider.analyze(pathname, {
// We aren't using the detected locale, so we can pass `undefined` because
// we don't need to infer the default locale.
defaultLocale: undefined,
})
return match.pathname return match.pathname
} }
} }
...@@ -12,13 +12,13 @@ import { ...@@ -12,13 +12,13 @@ import {
ManifestLoader, ManifestLoader,
} from './helpers/manifest-loaders/manifest-loader' } from './helpers/manifest-loaders/manifest-loader'
import { ManifestRouteMatcherProvider } from './manifest-route-matcher-provider' import { ManifestRouteMatcherProvider } from './manifest-route-matcher-provider'
import { LocaleRouteNormalizer } from '../normalizers/locale-route-normalizer' import { I18NProvider } from '../helpers/i18n-provider'
export class PagesAPIRouteMatcherProvider extends ManifestRouteMatcherProvider<PagesAPIRouteMatcher> { export class PagesAPIRouteMatcherProvider extends ManifestRouteMatcherProvider<PagesAPIRouteMatcher> {
constructor( constructor(
private readonly distDir: string, private readonly distDir: string,
manifestLoader: ManifestLoader, manifestLoader: ManifestLoader,
private readonly localeNormalizer?: LocaleRouteNormalizer private readonly i18nProvider?: I18NProvider
) { ) {
super(PAGES_MANIFEST, manifestLoader) super(PAGES_MANIFEST, manifestLoader)
} }
...@@ -34,9 +34,14 @@ export class PagesAPIRouteMatcherProvider extends ManifestRouteMatcherProvider<P ...@@ -34,9 +34,14 @@ export class PagesAPIRouteMatcherProvider extends ManifestRouteMatcherProvider<P
const matchers: Array<PagesAPIRouteMatcher> = [] const matchers: Array<PagesAPIRouteMatcher> = []
for (const page of pathnames) { for (const page of pathnames) {
if (this.localeNormalizer) { if (this.i18nProvider) {
// Match the locale on the page name, or default to the default locale. // Match the locale on the page name, or default to the default locale.
const { detectedLocale, pathname } = this.localeNormalizer.match(page) const { detectedLocale, pathname } = this.i18nProvider.analyze(page, {
// We don't need to assume a default locale here, since we're
// generating the routes which either should support a specific locale
// or any locale.
defaultLocale: undefined,
})
matchers.push( matchers.push(
new PagesAPILocaleRouteMatcher({ new PagesAPILocaleRouteMatcher({
......
import { PAGES_MANIFEST, SERVER_DIRECTORY } from '../../../shared/lib/constants' import { PAGES_MANIFEST, SERVER_DIRECTORY } from '../../../shared/lib/constants'
import { LocaleRouteNormalizer } from '../normalizers/locale-route-normalizer' import { I18NProvider } from '../helpers/i18n-provider'
import { PagesRouteDefinition } from '../route-definitions/pages-route-definition' import { PagesRouteDefinition } from '../route-definitions/pages-route-definition'
import { RouteKind } from '../route-kind' import { RouteKind } from '../route-kind'
import { ManifestLoader } from './helpers/manifest-loaders/manifest-loader' import { ManifestLoader } from './helpers/manifest-loaders/manifest-loader'
...@@ -17,7 +17,7 @@ describe('PagesRouteMatcherProvider', () => { ...@@ -17,7 +17,7 @@ describe('PagesRouteMatcherProvider', () => {
describe.each<{ describe.each<{
manifest: Record<string, string> manifest: Record<string, string>
routes: ReadonlyArray<PagesRouteDefinition> routes: ReadonlyArray<PagesRouteDefinition>
i18n: { locales: ReadonlyArray<string>; defaultLocale: string } i18n: { locales: Array<string>; defaultLocale: string }
}>([ }>([
{ {
manifest: { manifest: {
...@@ -116,7 +116,7 @@ describe('PagesRouteMatcherProvider', () => { ...@@ -116,7 +116,7 @@ describe('PagesRouteMatcherProvider', () => {
const provider = new PagesRouteMatcherProvider( const provider = new PagesRouteMatcherProvider(
'<root>', '<root>',
loader, loader,
new LocaleRouteNormalizer(i18n.locales, i18n.defaultLocale) new I18NProvider(i18n)
) )
const matchers = await provider.matchers() const matchers = await provider.matchers()
......
...@@ -6,7 +6,6 @@ import { ...@@ -6,7 +6,6 @@ import {
SERVER_DIRECTORY, SERVER_DIRECTORY,
} from '../../../shared/lib/constants' } from '../../../shared/lib/constants'
import { normalizePagePath } from '../../../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../../../shared/lib/page-path/normalize-page-path'
import { LocaleRouteNormalizer } from '../normalizers/locale-route-normalizer'
import { RouteKind } from '../route-kind' import { RouteKind } from '../route-kind'
import { import {
PagesLocaleRouteMatcher, PagesLocaleRouteMatcher,
...@@ -17,12 +16,13 @@ import { ...@@ -17,12 +16,13 @@ import {
ManifestLoader, ManifestLoader,
} from './helpers/manifest-loaders/manifest-loader' } from './helpers/manifest-loaders/manifest-loader'
import { ManifestRouteMatcherProvider } from './manifest-route-matcher-provider' import { ManifestRouteMatcherProvider } from './manifest-route-matcher-provider'
import { I18NProvider } from '../helpers/i18n-provider'
export class PagesRouteMatcherProvider extends ManifestRouteMatcherProvider<PagesRouteMatcher> { export class PagesRouteMatcherProvider extends ManifestRouteMatcherProvider<PagesRouteMatcher> {
constructor( constructor(
private readonly distDir: string, private readonly distDir: string,
manifestLoader: ManifestLoader, manifestLoader: ManifestLoader,
private readonly localeNormalizer?: LocaleRouteNormalizer private readonly i18nProvider?: I18NProvider
) { ) {
super(PAGES_MANIFEST, manifestLoader) super(PAGES_MANIFEST, manifestLoader)
} }
...@@ -38,7 +38,9 @@ export class PagesRouteMatcherProvider extends ManifestRouteMatcherProvider<Page ...@@ -38,7 +38,9 @@ export class PagesRouteMatcherProvider extends ManifestRouteMatcherProvider<Page
// internal pages). // internal pages).
.filter((pathname) => { .filter((pathname) => {
const normalized = const normalized =
this.localeNormalizer?.normalize(pathname) ?? pathname this.i18nProvider?.analyze(pathname, {
defaultLocale: undefined,
}).pathname ?? pathname
// Skip any blocked pages. // Skip any blocked pages.
if (BLOCKED_PAGES.includes(normalized)) return false if (BLOCKED_PAGES.includes(normalized)) return false
...@@ -48,9 +50,14 @@ export class PagesRouteMatcherProvider extends ManifestRouteMatcherProvider<Page ...@@ -48,9 +50,14 @@ export class PagesRouteMatcherProvider extends ManifestRouteMatcherProvider<Page
const matchers: Array<PagesRouteMatcher> = [] const matchers: Array<PagesRouteMatcher> = []
for (const page of pathnames) { for (const page of pathnames) {
if (this.localeNormalizer) { if (this.i18nProvider) {
// Match the locale on the page name, or default to the default locale. // Match the locale on the page name, or default to the default locale.
const { detectedLocale, pathname } = this.localeNormalizer.match(page) const { detectedLocale, pathname } = this.i18nProvider.analyze(page, {
// We don't need to assume a default locale here, since we're
// generating the routes which either should support a specific locale
// or any locale.
defaultLocale: undefined,
})
matchers.push( matchers.push(
new PagesLocaleRouteMatcher({ new PagesLocaleRouteMatcher({
......
...@@ -10,13 +10,21 @@ export type LocaleMatcherMatchOptions = { ...@@ -10,13 +10,21 @@ export type LocaleMatcherMatchOptions = {
*/ */
i18n?: { i18n?: {
/** /**
* The locale that was detected on the incoming route. If undefined it means * The locale that was detected on the incoming route. If `undefined` it
* that the locale should be considered to be the default one. * means that the locale should be considered to be the default one.
*
* For example, if the default locale is `en` and the incoming route is
* `/about`, then this would be `undefined`. If the incoming route was
* `/en/about`, then this would be `en`. If the incoming route was
* `/fr/about` then this would be `fr`.
*/ */
detectedLocale?: string detectedLocale?: string
/** /**
* The pathname that has had it's locale information stripped from. * The pathname that has had it's locale information stripped from it.
*
* For example, if the pathname previous was `/en/about` and the locale was
* `en`, then this would be `/about`.
*/ */
pathname: string pathname: string
} }
...@@ -34,6 +42,14 @@ export class LocaleRouteMatcher< ...@@ -34,6 +42,14 @@ export class LocaleRouteMatcher<
return `${this.definition.pathname}?__nextLocale=${this.definition.i18n?.locale}` return `${this.definition.pathname}?__nextLocale=${this.definition.i18n?.locale}`
} }
/**
* Match will attempt to match the given pathname against this route while
* also taking into account the locale information.
*
* @param pathname The pathname to match against.
* @param options The options to use when matching.
* @returns The match result, or `null` if there was no match.
*/
public match( public match(
pathname: string, pathname: string,
options?: LocaleMatcherMatchOptions options?: LocaleMatcherMatchOptions
...@@ -47,12 +63,23 @@ export class LocaleRouteMatcher< ...@@ -47,12 +63,23 @@ export class LocaleRouteMatcher<
definition: this.definition, definition: this.definition,
params: result.params, params: result.params,
detectedLocale: detectedLocale:
// If the options have a detected locale, then use that, otherwise use
// the route's locale.
options?.i18n?.detectedLocale ?? this.definition.i18n?.locale, options?.i18n?.detectedLocale ?? this.definition.i18n?.locale,
} }
} }
/**
* Test will attempt to match the given pathname against this route while
* also taking into account the locale information.
*
* @param pathname The pathname to match against.
* @param options The options to use when matching.
* @returns The match result, or `null` if there was no match.
*/
public test(pathname: string, options?: LocaleMatcherMatchOptions) { public test(pathname: string, options?: LocaleMatcherMatchOptions) {
// If this route has locale information... // If this route has locale information and we have detected a locale, then
// we need to compare the detected locale to the route's locale.
if (this.definition.i18n && options?.i18n) { if (this.definition.i18n && options?.i18n) {
// If we have detected a locale and it does not match this route's locale, // If we have detected a locale and it does not match this route's locale,
// then this isn't a match! // then this isn't a match!
...@@ -69,6 +96,8 @@ export class LocaleRouteMatcher< ...@@ -69,6 +96,8 @@ export class LocaleRouteMatcher<
return super.test(options.i18n.pathname) return super.test(options.i18n.pathname)
} }
// If we don't have locale information, then we can just perform regular
// matching.
return super.test(pathname) return super.test(pathname)
} }
} }
...@@ -8,6 +8,10 @@ import { getRouteRegex } from '../../../shared/lib/router/utils/route-regex' ...@@ -8,6 +8,10 @@ import { getRouteRegex } from '../../../shared/lib/router/utils/route-regex'
import { RouteDefinition } from '../route-definitions/route-definition' import { RouteDefinition } from '../route-definitions/route-definition'
import { RouteMatch } from '../route-matches/route-match' import { RouteMatch } from '../route-matches/route-match'
type RouteMatchResult = {
params?: Params
}
export class RouteMatcher<D extends RouteDefinition = RouteDefinition> { export class RouteMatcher<D extends RouteDefinition = RouteDefinition> {
private readonly dynamic?: RouteMatchFn private readonly dynamic?: RouteMatchFn
...@@ -44,7 +48,7 @@ export class RouteMatcher<D extends RouteDefinition = RouteDefinition> { ...@@ -44,7 +48,7 @@ export class RouteMatcher<D extends RouteDefinition = RouteDefinition> {
return { definition: this.definition, params: result.params } return { definition: this.definition, params: result.params }
} }
public test(pathname: string): { params?: Params } | null { public test(pathname: string): RouteMatchResult | null {
if (this.dynamic) { if (this.dynamic) {
const params = this.dynamic(pathname) const params = this.dynamic(pathname)
if (!params) return null if (!params) return null
......
...@@ -47,9 +47,6 @@ import { format as formatUrl, UrlWithParsedQuery } from 'url' ...@@ -47,9 +47,6 @@ import { format as formatUrl, UrlWithParsedQuery } from 'url'
import { getPathMatch } from '../shared/lib/router/utils/path-match' import { getPathMatch } from '../shared/lib/router/utils/path-match'
import { createHeaderRoute, createRedirectRoute } from './server-route-utils' import { createHeaderRoute, createRedirectRoute } from './server-route-utils'
import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-asset-path' import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-asset-path'
import { detectDomainLocale } from '../shared/lib/i18n/detect-domain-locale'
import { NodeNextRequest, NodeNextResponse } from './base-http/node' import { NodeNextRequest, NodeNextResponse } from './base-http/node'
import { sendRenderResult } from './send-payload' import { sendRenderResult } from './send-payload'
import { getExtension, serveStatic } from './serve-static' import { getExtension, serveStatic } from './serve-static'
...@@ -76,7 +73,6 @@ import { FontManifest } from './font-utils' ...@@ -76,7 +73,6 @@ import { FontManifest } from './font-utils'
import { splitCookiesString, toNodeHeaders } from './web/utils' import { splitCookiesString, toNodeHeaders } from './web/utils'
import { relativizeURL } from '../shared/lib/router/utils/relativize-url' import { relativizeURL } from '../shared/lib/router/utils/relativize-url'
import { prepareDestination } from '../shared/lib/router/utils/prepare-destination' import { prepareDestination } from '../shared/lib/router/utils/prepare-destination'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { getMiddlewareRouteMatcher } from '../shared/lib/router/utils/middleware-route-matcher' import { getMiddlewareRouteMatcher } from '../shared/lib/router/utils/middleware-route-matcher'
import { loadEnvConfig } from '@next/env' import { loadEnvConfig } from '@next/env'
import { getCustomRoute, stringifyQuery } from './server-route-utils' import { getCustomRoute, stringifyQuery } from './server-route-utils'
...@@ -1136,23 +1132,22 @@ export default class NextNodeServer extends BaseServer { ...@@ -1136,23 +1132,22 @@ export default class NextNodeServer extends BaseServer {
const { host } = req?.headers || {} const { host } = req?.headers || {}
// remove port from host and remove port if present // remove port from host and remove port if present
const hostname = host?.split(':')[0].toLowerCase() const hostname = host?.split(':')[0].toLowerCase()
const localePathResult = normalizeLocalePath(
pathname, const domainLocale = this.i18nProvider?.detectDomainLocale(hostname)
this.nextConfig.i18n.locales const localePathResult = this.i18nProvider?.analyze(pathname, {
) defaultLocale: undefined,
const { defaultLocale } = })
detectDomainLocale(this.nextConfig.i18n.domains, hostname) || {}
let detectedLocale = '' let detectedLocale = ''
if (localePathResult.detectedLocale) { if (localePathResult?.detectedLocale) {
pathname = localePathResult.pathname pathname = localePathResult.pathname
detectedLocale = localePathResult.detectedLocale detectedLocale = localePathResult.detectedLocale
} }
_parsedUrl.query.__nextLocale = detectedLocale _parsedUrl.query.__nextLocale = detectedLocale
_parsedUrl.query.__nextDefaultLocale = _parsedUrl.query.__nextDefaultLocale =
defaultLocale || this.nextConfig.i18n.defaultLocale domainLocale?.defaultLocale ?? this.nextConfig.i18n.defaultLocale
if (!detectedLocale && !this.router.catchAllMiddleware[0]) { if (!detectedLocale && !this.router.catchAllMiddleware[0]) {
_parsedUrl.query.__nextLocale = _parsedUrl.query.__nextLocale =
...@@ -1217,25 +1212,29 @@ export default class NextNodeServer extends BaseServer { ...@@ -1217,25 +1212,29 @@ export default class NextNodeServer extends BaseServer {
throw new Error('pathname is undefined') throw new Error('pathname is undefined')
} }
const bubbleNoFallback = Boolean(query._nextBubbleNoFallback)
// next.js core assumes page path without trailing slash // next.js core assumes page path without trailing slash
pathname = removeTrailingSlash(pathname) pathname = removeTrailingSlash(pathname)
const options: MatchOptions = { const options: MatchOptions = {
i18n: this.localeNormalizer?.match(pathname), i18n: this.i18nProvider?.analyze(pathname, {
defaultLocale: undefined,
}),
} }
if (options.i18n?.detectedLocale) { if (options.i18n?.detectedLocale) {
parsedUrl.query.__nextLocale = options.i18n.detectedLocale parsedUrl.query.__nextLocale = options.i18n.detectedLocale
} }
const bubbleNoFallback = !!query._nextBubbleNoFallback
const match = await this.matchers.match(pathname, options) const match = await this.matchers.match(pathname, options)
// Try to handle the given route with the configured handlers.
if (match) { if (match) {
// Add the match to the request so we don't have to re-run the matcher
// for the same request.
addRequestMeta(req, '_nextMatch', match) addRequestMeta(req, '_nextMatch', match)
}
// Try to handle the given route with the configured handlers.
if (match) {
// TODO-APP: move this to a route handler // TODO-APP: move this to a route handler
const edgeFunctionsPages = this.getEdgeFunctionsPages() const edgeFunctionsPages = this.getEdgeFunctionsPages()
for (const edgeFunctionsPage of edgeFunctionsPages) { for (const edgeFunctionsPage of edgeFunctionsPages) {
...@@ -1320,7 +1319,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -1320,7 +1319,7 @@ export default class NextNodeServer extends BaseServer {
useFileSystemPublicRoutes, useFileSystemPublicRoutes,
matchers: this.matchers, matchers: this.matchers,
nextConfig: this.nextConfig, nextConfig: this.nextConfig,
localeNormalizer: this.localeNormalizer, i18nProvider: this.i18nProvider,
} }
} }
...@@ -1761,7 +1760,9 @@ export default class NextNodeServer extends BaseServer { ...@@ -1761,7 +1760,9 @@ export default class NextNodeServer extends BaseServer {
let url: string let url: string
const options: MatchOptions = { const options: MatchOptions = {
i18n: this.localeNormalizer?.match(normalizedPathname), i18n: this.i18nProvider?.analyze(normalizedPathname, {
defaultLocale: undefined,
}),
} }
if (this.nextConfig.skipMiddlewareUrlNormalize) { if (this.nextConfig.skipMiddlewareUrlNormalize) {
url = getRequestMeta(params.request, '__NEXT_INIT_URL')! url = getRequestMeta(params.request, '__NEXT_INIT_URL')!
...@@ -1890,6 +1891,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -1890,6 +1891,7 @@ export default class NextNodeServer extends BaseServer {
const parsedUrl = parseUrl(initUrl) const parsedUrl = parseUrl(initUrl)
const pathnameInfo = getNextPathnameInfo(parsedUrl.pathname, { const pathnameInfo = getNextPathnameInfo(parsedUrl.pathname, {
nextConfig: this.nextConfig, nextConfig: this.nextConfig,
i18nProvider: this.i18nProvider,
}) })
parsedUrl.pathname = pathnameInfo.pathname parsedUrl.pathname = pathnameInfo.pathname
...@@ -2040,14 +2042,12 @@ export default class NextNodeServer extends BaseServer { ...@@ -2040,14 +2042,12 @@ export default class NextNodeServer extends BaseServer {
) )
} }
if (this.nextConfig.i18n) { if (this.i18nProvider) {
const localePathResult = normalizeLocalePath( const { detectedLocale } = this.i18nProvider.analyze(newUrl, {
newUrl, defaultLocale: undefined,
this.nextConfig.i18n.locales })
) if (detectedLocale) {
if (localePathResult.detectedLocale) { parsedDestination.query.__nextLocale = detectedLocale
parsedDestination.query.__nextLocale =
localePathResult.detectedLocale
} }
} }
......
...@@ -17,7 +17,17 @@ export interface RequestMeta { ...@@ -17,7 +17,17 @@ export interface RequestMeta {
__NEXT_INIT_URL?: string __NEXT_INIT_URL?: string
__NEXT_CLONABLE_BODY?: CloneableBody __NEXT_CLONABLE_BODY?: CloneableBody
__nextHadTrailingSlash?: boolean __nextHadTrailingSlash?: boolean
/**
* True when the request matched a locale domain that was configured in the
* next.config.js file.
*/
__nextIsLocaleDomain?: boolean __nextIsLocaleDomain?: boolean
/**
* True when the request had locale information stripped from the pathname
* part of the URL.
*/
__nextStrippedLocale?: boolean __nextStrippedLocale?: boolean
_nextDidRewrite?: boolean _nextDidRewrite?: boolean
_nextHadBasePath?: boolean _nextHadBasePath?: boolean
......
...@@ -24,7 +24,7 @@ import { ...@@ -24,7 +24,7 @@ import {
RouteMatcherManager, RouteMatcherManager,
} from './future/route-matcher-managers/route-matcher-manager' } from './future/route-matcher-managers/route-matcher-manager'
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash' import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
import { LocaleRouteNormalizer } from './future/normalizers/locale-route-normalizer' import type { I18NProvider } from './future/helpers/i18n-provider'
import { getTracer } from './lib/trace/tracer' import { getTracer } from './lib/trace/tracer'
import { RouterSpan } from './lib/trace/constants' import { RouterSpan } from './lib/trace/constants'
...@@ -34,6 +34,14 @@ type RouteResult = { ...@@ -34,6 +34,14 @@ type RouteResult = {
query?: ParsedUrlQuery query?: ParsedUrlQuery
} }
type RouteFn = (
req: BaseNextRequest,
res: BaseNextResponse,
params: Params,
parsedUrl: NextUrlWithParsedQuery,
upgradeHead?: Buffer
) => Promise<RouteResult> | RouteResult
export type Route = { export type Route = {
match: RouteMatchFn match: RouteMatchFn
has?: RouteHas[] has?: RouteHas[]
...@@ -47,13 +55,7 @@ export type Route = { ...@@ -47,13 +55,7 @@ export type Route = {
matchesLocaleAPIRoutes?: true matchesLocaleAPIRoutes?: true
matchesTrailingSlash?: true matchesTrailingSlash?: true
internal?: true internal?: true
fn: ( fn: RouteFn
req: BaseNextRequest,
res: BaseNextResponse,
params: Params,
parsedUrl: NextUrlWithParsedQuery,
upgradeHead?: Buffer
) => Promise<RouteResult> | RouteResult
} }
export type RouterOptions = { export type RouterOptions = {
...@@ -70,7 +72,7 @@ export type RouterOptions = { ...@@ -70,7 +72,7 @@ export type RouterOptions = {
matchers: RouteMatcherManager matchers: RouteMatcherManager
useFileSystemPublicRoutes: boolean useFileSystemPublicRoutes: boolean
nextConfig: NextConfig nextConfig: NextConfig
localeNormalizer?: LocaleRouteNormalizer i18nProvider?: I18NProvider
} }
export type PageChecker = (pathname: string) => Promise<boolean> export type PageChecker = (pathname: string) => Promise<boolean>
...@@ -87,10 +89,10 @@ export default class Router { ...@@ -87,10 +89,10 @@ export default class Router {
fallback: ReadonlyArray<Route> fallback: ReadonlyArray<Route>
} }
private readonly catchAllRoute: Route private readonly catchAllRoute: Route
private readonly matchers: Pick<RouteMatcherManager, 'test'> private readonly matchers: RouteMatcherManager
private readonly useFileSystemPublicRoutes: boolean private readonly useFileSystemPublicRoutes: boolean
private readonly nextConfig: NextConfig private readonly nextConfig: NextConfig
private readonly localeNormalizer?: LocaleRouteNormalizer private readonly i18nProvider?: I18NProvider
private compiledRoutes: ReadonlyArray<Route> private compiledRoutes: ReadonlyArray<Route>
private needsRecompilation: boolean private needsRecompilation: boolean
...@@ -108,7 +110,7 @@ export default class Router { ...@@ -108,7 +110,7 @@ export default class Router {
matchers, matchers,
useFileSystemPublicRoutes, useFileSystemPublicRoutes,
nextConfig, nextConfig,
localeNormalizer, i18nProvider,
}: RouterOptions) { }: RouterOptions) {
this.nextConfig = nextConfig this.nextConfig = nextConfig
this.headers = headers this.headers = headers
...@@ -119,7 +121,7 @@ export default class Router { ...@@ -119,7 +121,7 @@ export default class Router {
this.catchAllMiddleware = catchAllMiddleware this.catchAllMiddleware = catchAllMiddleware
this.matchers = matchers this.matchers = matchers
this.useFileSystemPublicRoutes = useFileSystemPublicRoutes this.useFileSystemPublicRoutes = useFileSystemPublicRoutes
this.localeNormalizer = localeNormalizer this.i18nProvider = i18nProvider
// Perform the initial route compilation. // Perform the initial route compilation.
this.compiledRoutes = this.compileRoutes() this.compiledRoutes = this.compileRoutes()
...@@ -176,6 +178,7 @@ export default class Router { ...@@ -176,6 +178,7 @@ export default class Router {
? [ ? [
{ {
type: 'route', type: 'route',
matchesLocale: true,
name: 'page checker', name: 'page checker',
match: getPathMatch('/:path*'), match: getPathMatch('/:path*'),
fn: async (req, res, params, parsedUrl, upgradeHead) => { fn: async (req, res, params, parsedUrl, upgradeHead) => {
...@@ -188,15 +191,17 @@ export default class Router { ...@@ -188,15 +191,17 @@ export default class Router {
// step we're processing the afterFiles rewrites which must // step we're processing the afterFiles rewrites which must
// not include dynamic matches. // not include dynamic matches.
skipDynamic: true, skipDynamic: true,
i18n: this.localeNormalizer?.match(pathname, { i18n: this.i18nProvider?.analyze(pathname, {
// TODO: verify changing the default locale defaultLocale: undefined,
inferDefaultLocale: true,
}), }),
} }
const match = await this.matchers.test(pathname, options) const match = await this.matchers.match(pathname, options)
if (!match) return { finished: false } if (!match) return { finished: false }
// Add the match so we can get it later.
addRequestMeta(req, '_nextMatch', match)
return this.catchAllRoute.fn( return this.catchAllRoute.fn(
req, req,
res, res,
...@@ -275,9 +280,8 @@ export default class Router { ...@@ -275,9 +280,8 @@ export default class Router {
// Normalize and detect the locale on the pathname. // Normalize and detect the locale on the pathname.
const options: MatchOptions = { const options: MatchOptions = {
i18n: this.localeNormalizer?.match(fsPathname, { i18n: this.i18nProvider?.analyze(fsPathname, {
// TODO: verify changing the default locale defaultLocale: undefined,
inferDefaultLocale: true,
}), }),
} }
...@@ -351,23 +355,27 @@ export default class Router { ...@@ -351,23 +355,27 @@ export default class Router {
continue continue
} }
// Update the `basePath` if the request had a `basePath`.
if (getRequestMeta(req, '_nextHadBasePath')) { if (getRequestMeta(req, '_nextHadBasePath')) {
pathnameInfo.basePath = this.basePath pathnameInfo.basePath = this.basePath
} }
// Create a copy of the `basePath` so we can modify it for the next
// request if the route doesn't match with the `basePath`.
const basePath = pathnameInfo.basePath const basePath = pathnameInfo.basePath
if (!route.matchesBasePath) { if (!route.matchesBasePath) {
pathnameInfo.basePath = '' pathnameInfo.basePath = ''
} }
if ( // Add the locale to the information if the route supports matching
route.matchesLocale && // locales and the locale is not present in the info.
parsedUrlUpdated.query.__nextLocale && const locale = parsedUrlUpdated.query.__nextLocale
!pathnameInfo.locale if (route.matchesLocale && locale && !pathnameInfo.locale) {
) { pathnameInfo.locale = locale
pathnameInfo.locale = parsedUrlUpdated.query.__nextLocale
} }
// If the route doesn't support matching locales and the locale is the
// default locale then remove it from the info.
if ( if (
!route.matchesLocale && !route.matchesLocale &&
pathnameInfo.locale === this.nextConfig.i18n?.defaultLocale && pathnameInfo.locale === this.nextConfig.i18n?.defaultLocale &&
...@@ -376,6 +384,8 @@ export default class Router { ...@@ -376,6 +384,8 @@ export default class Router {
pathnameInfo.locale = undefined pathnameInfo.locale = undefined
} }
// If the route doesn't support trailing slashes and the request had a
// trailing slash then remove it from the info.
if ( if (
route.matchesTrailingSlash && route.matchesTrailingSlash &&
getRequestMeta(req, '__nextHadTrailingSlash') getRequestMeta(req, '__nextHadTrailingSlash')
...@@ -383,6 +393,7 @@ export default class Router { ...@@ -383,6 +393,7 @@ export default class Router {
pathnameInfo.trailingSlash = true pathnameInfo.trailingSlash = true
} }
// Construct a new pathname based on the info.
const matchPathname = formatNextPathnameInfo({ const matchPathname = formatNextPathnameInfo({
ignorePrefix: true, ignorePrefix: true,
...pathnameInfo, ...pathnameInfo,
...@@ -403,11 +414,9 @@ export default class Router { ...@@ -403,11 +414,9 @@ export default class Router {
} }
} }
/** // If it is a matcher that doesn't match the basePath (like the public
* If it is a matcher that doesn't match the basePath (like the public // directory) but Next.js is configured to use a basePath that was
* directory) but Next.js is configured to use a basePath that was // never there, we consider this an invalid match and keep routing.
* never there, we consider this an invalid match and keep routing.
*/
if ( if (
params && params &&
this.basePath && this.basePath &&
...@@ -440,6 +449,8 @@ export default class Router { ...@@ -440,6 +449,8 @@ export default class Router {
return true return true
} }
// If the result includes a pathname then we need to update the
// parsed url pathname to continue routing.
if (result.pathname) { if (result.pathname) {
parsedUrlUpdated.pathname = result.pathname parsedUrlUpdated.pathname = result.pathname
} else { } else {
...@@ -448,6 +459,8 @@ export default class Router { ...@@ -448,6 +459,8 @@ export default class Router {
parsedUrlUpdated.pathname = originalPathname parsedUrlUpdated.pathname = originalPathname
} }
// Copy over only internal query parameters from the original query and
// merge with the result query.
if (result.query) { if (result.query) {
parsedUrlUpdated.query = { parsedUrlUpdated.query = {
...getNextInternalQuery(parsedUrlUpdated.query), ...getNextInternalQuery(parsedUrlUpdated.query),
......
...@@ -17,7 +17,6 @@ import WebResponseCache from './response-cache/web' ...@@ -17,7 +17,6 @@ import WebResponseCache from './response-cache/web'
import { isAPIRoute } from '../lib/is-api-route' import { isAPIRoute } from '../lib/is-api-route'
import { getPathMatch } from '../shared/lib/router/utils/path-match' import { getPathMatch } from '../shared/lib/router/utils/path-match'
import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-asset-path' import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-asset-path'
import { detectDomainLocale } from '../shared/lib/i18n/detect-domain-locale'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash' import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
import { isDynamicRoute } from '../shared/lib/router/utils' import { isDynamicRoute } from '../shared/lib/router/utils'
...@@ -235,8 +234,7 @@ export default class NextWebServer extends BaseServer<WebServerOptions> { ...@@ -235,8 +234,7 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
pathname, pathname,
this.nextConfig.i18n.locales this.nextConfig.i18n.locales
) )
const { defaultLocale } = const domainLocale = this.i18nProvider?.detectDomainLocale(hostname)
detectDomainLocale(this.nextConfig.i18n.domains, hostname) || {}
let detectedLocale = '' let detectedLocale = ''
...@@ -247,7 +245,7 @@ export default class NextWebServer extends BaseServer<WebServerOptions> { ...@@ -247,7 +245,7 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
_parsedUrl.query.__nextLocale = detectedLocale _parsedUrl.query.__nextLocale = detectedLocale
_parsedUrl.query.__nextDefaultLocale = _parsedUrl.query.__nextDefaultLocale =
defaultLocale || this.nextConfig.i18n.defaultLocale domainLocale?.defaultLocale || this.nextConfig.i18n.defaultLocale
if (!detectedLocale && !this.router.catchAllMiddleware[0]) { if (!detectedLocale && !this.router.catchAllMiddleware[0]) {
_parsedUrl.query.__nextLocale = _parsedUrl.query.__nextLocale =
...@@ -310,16 +308,15 @@ export default class NextWebServer extends BaseServer<WebServerOptions> { ...@@ -310,16 +308,15 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
// next.js core assumes page path without trailing slash // next.js core assumes page path without trailing slash
pathname = removeTrailingSlash(pathname) pathname = removeTrailingSlash(pathname)
if (this.nextConfig.i18n) { if (this.i18nProvider) {
const localePathResult = normalizeLocalePath( const { detectedLocale } = await this.i18nProvider.analyze(pathname, {
pathname, defaultLocale: undefined,
this.nextConfig.i18n?.locales })
) if (detectedLocale) {
parsedUrl.query.__nextLocale = detectedLocale
if (localePathResult.detectedLocale) {
parsedUrl.query.__nextLocale = localePathResult.detectedLocale
} }
} }
const bubbleNoFallback = !!query._nextBubbleNoFallback const bubbleNoFallback = !!query._nextBubbleNoFallback
if (isAPIRoute(pathname)) { if (isAPIRoute(pathname)) {
......
...@@ -3,6 +3,7 @@ import { detectDomainLocale } from '../../shared/lib/i18n/detect-domain-locale' ...@@ -3,6 +3,7 @@ import { detectDomainLocale } from '../../shared/lib/i18n/detect-domain-locale'
import { formatNextPathnameInfo } from '../../shared/lib/router/utils/format-next-pathname-info' import { formatNextPathnameInfo } from '../../shared/lib/router/utils/format-next-pathname-info'
import { getHostname } from '../../shared/lib/get-hostname' import { getHostname } from '../../shared/lib/get-hostname'
import { getNextPathnameInfo } from '../../shared/lib/router/utils/get-next-pathname-info' import { getNextPathnameInfo } from '../../shared/lib/router/utils/get-next-pathname-info'
import type { I18NProvider } from '../future/helpers/i18n-provider'
interface Options { interface Options {
base?: string | URL base?: string | URL
...@@ -13,6 +14,7 @@ interface Options { ...@@ -13,6 +14,7 @@ interface Options {
i18n?: I18NConfig | null i18n?: I18NConfig | null
trailingSlash?: boolean trailingSlash?: boolean
} }
i18nProvider?: I18NProvider
} }
const REGEX_LOCALHOST_HOSTNAME = const REGEX_LOCALHOST_HOSTNAME =
...@@ -28,7 +30,7 @@ function parseURL(url: string | URL, base?: string | URL) { ...@@ -28,7 +30,7 @@ function parseURL(url: string | URL, base?: string | URL) {
const Internal = Symbol('NextURLInternal') const Internal = Symbol('NextURLInternal')
export class NextURL { export class NextURL {
[Internal]: { private [Internal]: {
basePath: string basePath: string
buildId?: string buildId?: string
flightSearchParameters?: Record<string, string> flightSearchParameters?: Record<string, string>
...@@ -66,30 +68,37 @@ export class NextURL { ...@@ -66,30 +68,37 @@ export class NextURL {
basePath: '', basePath: '',
} }
this.analyzeUrl() this.analyze()
} }
private analyzeUrl() { private analyze() {
const pathnameInfo = getNextPathnameInfo(this[Internal].url.pathname, { const info = getNextPathnameInfo(this[Internal].url.pathname, {
nextConfig: this[Internal].options.nextConfig, nextConfig: this[Internal].options.nextConfig,
parseData: !process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE, parseData: !process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE,
i18nProvider: this[Internal].options.i18nProvider,
}) })
this[Internal].domainLocale = detectDomainLocale( const hostname = getHostname(
this[Internal].options.nextConfig?.i18n?.domains, this[Internal].url,
getHostname(this[Internal].url, this[Internal].options.headers) this[Internal].options.headers
) )
this[Internal].domainLocale = this[Internal].options.i18nProvider
? this[Internal].options.i18nProvider.detectDomainLocale(hostname)
: detectDomainLocale(
this[Internal].options.nextConfig?.i18n?.domains,
hostname
)
const defaultLocale = const defaultLocale =
this[Internal].domainLocale?.defaultLocale || this[Internal].domainLocale?.defaultLocale ||
this[Internal].options.nextConfig?.i18n?.defaultLocale this[Internal].options.nextConfig?.i18n?.defaultLocale
this[Internal].url.pathname = pathnameInfo.pathname this[Internal].url.pathname = info.pathname
this[Internal].defaultLocale = defaultLocale this[Internal].defaultLocale = defaultLocale
this[Internal].basePath = pathnameInfo.basePath ?? '' this[Internal].basePath = info.basePath ?? ''
this[Internal].buildId = pathnameInfo.buildId this[Internal].buildId = info.buildId
this[Internal].locale = pathnameInfo.locale ?? defaultLocale this[Internal].locale = info.locale ?? defaultLocale
this[Internal].trailingSlash = pathnameInfo.trailingSlash this[Internal].trailingSlash = info.trailingSlash
} }
private formatPathname() { private formatPathname() {
...@@ -186,7 +195,7 @@ export class NextURL { ...@@ -186,7 +195,7 @@ export class NextURL {
set href(url: string) { set href(url: string) {
this[Internal].url = parseURL(url) this[Internal].url = parseURL(url)
this.analyzeUrl() this.analyze()
} }
get origin() { get origin() {
......
...@@ -5,26 +5,21 @@ export function detectDomainLocale( ...@@ -5,26 +5,21 @@ export function detectDomainLocale(
hostname?: string, hostname?: string,
detectedLocale?: string detectedLocale?: string
) { ) {
let domainItem: DomainLocale | undefined if (!domainItems) return
if (domainItems) { if (detectedLocale) {
if (detectedLocale) { detectedLocale = detectedLocale.toLowerCase()
detectedLocale = detectedLocale.toLowerCase() }
}
for (const item of domainItems) { for (const item of domainItems) {
// remove port if present // remove port if present
const domainHostname = item.domain?.split(':')[0].toLowerCase() const domainHostname = item.domain?.split(':')[0].toLowerCase()
if ( if (
hostname === domainHostname || hostname === domainHostname ||
detectedLocale === item.defaultLocale.toLowerCase() || detectedLocale === item.defaultLocale.toLowerCase() ||
item.locales?.some((locale) => locale.toLowerCase() === detectedLocale) item.locales?.some((locale) => locale.toLowerCase() === detectedLocale)
) { ) {
domainItem = item return item
break
}
} }
} }
return domainItem
} }
...@@ -12,15 +12,19 @@ export function addLocale( ...@@ -12,15 +12,19 @@ export function addLocale(
defaultLocale?: string, defaultLocale?: string,
ignorePrefix?: boolean ignorePrefix?: boolean
) { ) {
if ( // If no locale was given or the locale is the default locale, we don't need
locale && // to prefix the path.
locale !== defaultLocale && if (!locale || locale === defaultLocale) return path
(ignorePrefix ||
(!pathHasPrefix(path.toLowerCase(), `/${locale.toLowerCase()}`) && const lower = path.toLowerCase()
!pathHasPrefix(path.toLowerCase(), '/api')))
) { // If the path is an API path or the path already has the locale prefix, we
return addPathPrefix(path, `/${locale}`) // don't need to prefix the path.
if (!ignorePrefix) {
if (pathHasPrefix(lower, '/api')) return path
if (pathHasPrefix(lower, `/${locale.toLowerCase()}`)) return path
} }
return path // Add the locale prefix to the path.
return addPathPrefix(path, `/${locale}`)
} }
import { normalizeLocalePath } from '../../i18n/normalize-locale-path' import { normalizeLocalePath } from '../../i18n/normalize-locale-path'
import { removePathPrefix } from './remove-path-prefix' import { removePathPrefix } from './remove-path-prefix'
import { pathHasPrefix } from './path-has-prefix' import { pathHasPrefix } from './path-has-prefix'
import { I18NProvider } from '../../../../server/future/helpers/i18n-provider'
export interface NextPathnameInfo { export interface NextPathnameInfo {
/** /**
...@@ -41,6 +42,12 @@ interface Options { ...@@ -41,6 +42,12 @@ interface Options {
i18n?: { locales?: string[] } | null i18n?: { locales?: string[] } | null
trailingSlash?: boolean trailingSlash?: boolean
} }
/**
* If provided, this normalizer will be used to detect the locale instead of
* the default locale detection.
*/
i18nProvider?: I18NProvider
} }
export function getNextPathnameInfo(pathname: string, options: Options) { export function getNextPathnameInfo(pathname: string, options: Options) {
...@@ -70,10 +77,20 @@ export function getNextPathnameInfo(pathname: string, options: Options) { ...@@ -70,10 +77,20 @@ export function getNextPathnameInfo(pathname: string, options: Options) {
info.buildId = buildId info.buildId = buildId
} }
if (i18n) { // If provided, use the locale route normalizer to detect the locale instead
// of the function below.
if (options.i18nProvider) {
const result = options.i18nProvider.analyze(info.pathname, {
// We set this to undefined because the default locale detection is
// completed out of this function.
defaultLocale: undefined,
})
info.locale = result.detectedLocale
info.pathname = result.pathname ?? info.pathname
} else if (i18n) {
const pathLocale = normalizeLocalePath(info.pathname, i18n.locales) const pathLocale = normalizeLocalePath(info.pathname, i18n.locales)
info.locale = pathLocale?.detectedLocale info.locale = pathLocale.detectedLocale
info.pathname = pathLocale?.pathname || info.pathname info.pathname = pathLocale.pathname ?? info.pathname
} }
return info return info
......
import { createNextDescribe } from 'e2e-utils'
import cheerio from 'cheerio'
const config = require('./next.config')
async function verify(res, locale) {
expect(res.status).toBe(200)
// Verify that we loaded the right page and the locale is correct.
const html = await res.text()
const $ = cheerio.load(html)
expect($('#page').text()).toBe('index page')
expect($('#router-locale').text()).toBe(locale)
}
createNextDescribe(
'i18n-disallow-multiple-locales',
{
files: __dirname,
},
({ next }) => {
it('should verify the default locale works', async () => {
const res = await next.fetch('/', { redirect: 'manual' })
await verify(res, config.i18n.defaultLocale)
})
it.each(config.i18n.locales)('/%s should 200', async (locale) => {
const res = await next.fetch(`/${locale}`, { redirect: 'manual' })
await verify(res, locale)
})
it.each(
config.i18n.locales.reduce((locales, firstLocale) => {
for (const secondLocale of config.i18n.locales) {
locales.push([firstLocale, secondLocale])
}
return locales
}, [])
)('/%s/%s should 404', async (firstLocale, secondLocale) => {
// Ensure that the double locale does not work.
const res = await next.fetch(`/${firstLocale}/${secondLocale}`, {
redirect: 'manual',
})
expect(res.status).toBe(404)
})
}
)
module.exports = {
i18n: {
locales: ['en-US', 'en', 'nl-NL', 'nl-BE', 'nl', 'fr-BE', 'fr'],
defaultLocale: 'en-US',
},
}
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
return (
<div>
<p id="page">index page</p>
<p id="router-locale">{router.locale}</p>
</div>
)
}
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