Unverified Commit bbc1a21c authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update to have default locale matched on root (#17669)

Follow-up PR to https://github.com/vercel/next.js/pull/17370 when the path is not prefixed with a locale and the default locale is the detected locale it doesn't redirect to locale prefixed variant. If the default locale path is visited and the default locale is visited this also redirects to the root removing the un-necessary locale in the URL. 

This also exposes the `defaultLocale` on the router since the RFC mentions `Setting a defaultLocale is required in every i18n library so it'd be useful for Next.js to provide it to the application.` although doesn't explicitly spec where we want to expose it. If we want to expose it differently this can be updated. 
parent a79bcfb7
...@@ -229,24 +229,34 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -229,24 +229,34 @@ const nextServerlessLoader: loader.Loader = function () {
detectedLocale = accept.language( detectedLocale = accept.language(
req.headers['accept-language'], req.headers['accept-language'],
i18n.locales i18n.locales
) || i18n.defaultLocale )
} }
const denormalizedPagePath = denormalizePagePath(parsedUrl.pathname || '/')
const detectedDefaultLocale = detectedLocale === i18n.defaultLocale
const shouldStripDefaultLocale =
detectedDefaultLocale &&
denormalizedPagePath === \`/\${i18n.defaultLocale}\`
const shouldAddLocalePrefix =
!detectedDefaultLocale && denormalizedPagePath === '/'
detectedLocale = detectedLocale || i18n.defaultLocale
if ( if (
!nextStartMode && !nextStartMode &&
i18n.localeDetection !== false && i18n.localeDetection !== false &&
denormalizePagePath(parsedUrl.pathname || '/') === '/' (shouldAddLocalePrefix || shouldStripDefaultLocale)
) { ) {
res.setHeader( res.setHeader(
'Location', 'Location',
formatUrl({ formatUrl({
// make sure to include any query values when redirecting // make sure to include any query values when redirecting
...parsedUrl, ...parsedUrl,
pathname: \`/\${detectedLocale}\`, pathname: shouldStripDefaultLocale ? '/' : \`/\${detectedLocale}\`,
}) })
) )
res.statusCode = 307 res.statusCode = 307
res.end() res.end()
return
} }
// TODO: domain based locales (domain to locale mapping needs to be provided in next.config.js) // TODO: domain based locales (domain to locale mapping needs to be provided in next.config.js)
...@@ -458,6 +468,7 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -458,6 +468,7 @@ const nextServerlessLoader: loader.Loader = function () {
isDataReq: _nextData, isDataReq: _nextData,
locale: detectedLocale, locale: detectedLocale,
locales: i18n.locales, locales: i18n.locales,
defaultLocale: i18n.defaultLocale,
}, },
options, options,
) )
......
...@@ -65,6 +65,7 @@ const { ...@@ -65,6 +65,7 @@ const {
isFallback, isFallback,
head: initialHeadData, head: initialHeadData,
locales, locales,
defaultLocale,
} = data } = data
let { locale } = data let { locale } = data
...@@ -317,6 +318,7 @@ export default async (opts: { webpackHMR?: any } = {}) => { ...@@ -317,6 +318,7 @@ export default async (opts: { webpackHMR?: any } = {}) => {
render({ App, Component, styleSheets, props, err }), render({ App, Component, styleSheets, props, err }),
locale, locale,
locales, locales,
defaultLocale,
}) })
// call init-client middleware // call init-client middleware
......
...@@ -332,7 +332,9 @@ function Link(props: React.PropsWithChildren<LinkProps>) { ...@@ -332,7 +332,9 @@ function Link(props: React.PropsWithChildren<LinkProps>) {
// If child is an <a> tag and doesn't have a href attribute, or if the 'passHref' property is // If child is an <a> tag and doesn't have a href attribute, or if the 'passHref' property is
// defined, we specify the current 'href', so that repetition is not needed by the user // defined, we specify the current 'href', so that repetition is not needed by the user
if (props.passHref || (child.type === 'a' && !('href' in child.props))) { if (props.passHref || (child.type === 'a' && !('href' in child.props))) {
childProps.href = addBasePath(addLocale(as, router && router.locale)) childProps.href = addBasePath(
addLocale(as, router && router.locale, router && router.defaultLocale)
)
} }
return React.cloneElement(child, childProps) return React.cloneElement(child, childProps)
......
...@@ -203,13 +203,23 @@ export default class PageLoader { ...@@ -203,13 +203,23 @@ export default class PageLoader {
* @param {string} href the route href (file-system path) * @param {string} href the route href (file-system path)
* @param {string} asPath the URL as shown in browser (virtual path); used for dynamic routes * @param {string} asPath the URL as shown in browser (virtual path); used for dynamic routes
*/ */
getDataHref(href: string, asPath: string, ssg: boolean, locale?: string) { getDataHref(
href: string,
asPath: string,
ssg: boolean,
locale?: string,
defaultLocale?: string
) {
const { pathname: hrefPathname, query, search } = parseRelativeUrl(href) const { pathname: hrefPathname, query, search } = parseRelativeUrl(href)
const { pathname: asPathname } = parseRelativeUrl(asPath) const { pathname: asPathname } = parseRelativeUrl(asPath)
const route = normalizeRoute(hrefPathname) const route = normalizeRoute(hrefPathname)
const getHrefForSlug = (path: string) => { const getHrefForSlug = (path: string) => {
const dataRoute = addLocale(getAssetPathFromRoute(path, '.json'), locale) const dataRoute = addLocale(
getAssetPathFromRoute(path, '.json'),
locale,
defaultLocale
)
return addBasePath( return addBasePath(
`/_next/data/${this.buildId}${dataRoute}${ssg ? '' : search}` `/_next/data/${this.buildId}${dataRoute}${ssg ? '' : search}`
) )
...@@ -229,7 +239,12 @@ export default class PageLoader { ...@@ -229,7 +239,12 @@ export default class PageLoader {
* @param {string} href the route href (file-system path) * @param {string} href the route href (file-system path)
* @param {string} asPath the URL as shown in browser (virtual path); used for dynamic routes * @param {string} asPath the URL as shown in browser (virtual path); used for dynamic routes
*/ */
prefetchData(href: string, asPath: string) { prefetchData(
href: string,
asPath: string,
locale?: string,
defaultLocale?: string
) {
const { pathname: hrefPathname } = parseRelativeUrl(href) const { pathname: hrefPathname } = parseRelativeUrl(href)
const route = normalizeRoute(hrefPathname) const route = normalizeRoute(hrefPathname)
return this.promisedSsgManifest!.then( return this.promisedSsgManifest!.then(
...@@ -237,7 +252,13 @@ export default class PageLoader { ...@@ -237,7 +252,13 @@ export default class PageLoader {
// Check if the route requires a data file // Check if the route requires a data file
s.has(route) && s.has(route) &&
// Try to generate data href, noop when falsy // Try to generate data href, noop when falsy
(_dataHref = this.getDataHref(href, asPath, true)) && (_dataHref = this.getDataHref(
href,
asPath,
true,
locale,
defaultLocale
)) &&
// noop when data has already been prefetched (dedupe) // noop when data has already been prefetched (dedupe)
!document.querySelector( !document.querySelector(
`link[rel="${relPrefetch}"][href^="${_dataHref}"]` `link[rel="${relPrefetch}"][href^="${_dataHref}"]`
......
...@@ -39,6 +39,7 @@ const urlPropertyFields = [ ...@@ -39,6 +39,7 @@ const urlPropertyFields = [
'basePath', 'basePath',
'locale', 'locale',
'locales', 'locales',
'defaultLocale',
] ]
const routerEvents = [ const routerEvents = [
'routeChangeStart', 'routeChangeStart',
......
...@@ -283,6 +283,8 @@ export default async function exportApp( ...@@ -283,6 +283,8 @@ export default async function exportApp(
} }
} }
const { i18n } = nextConfig.experimental
// Start the rendering process // Start the rendering process
const renderOpts = { const renderOpts = {
dir, dir,
...@@ -298,8 +300,9 @@ export default async function exportApp( ...@@ -298,8 +300,9 @@ export default async function exportApp(
ampValidatorPath: nextConfig.experimental.amp?.validator || undefined, ampValidatorPath: nextConfig.experimental.amp?.validator || undefined,
ampSkipValidation: nextConfig.experimental.amp?.skipValidation || false, ampSkipValidation: nextConfig.experimental.amp?.skipValidation || false,
ampOptimizerConfig: nextConfig.experimental.amp?.optimizer || undefined, ampOptimizerConfig: nextConfig.experimental.amp?.optimizer || undefined,
locales: nextConfig.experimental.i18n?.locales, locales: i18n?.locales,
locale: nextConfig.experimental.i18n?.defaultLocale, locale: i18n.defaultLocale,
defaultLocale: i18n.defaultLocale,
} }
const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
......
...@@ -6,10 +6,14 @@ export function normalizeLocalePath( ...@@ -6,10 +6,14 @@ export function normalizeLocalePath(
pathname: string pathname: string
} { } {
let detectedLocale: string | undefined let detectedLocale: string | undefined
// first item will be empty string from splitting at first char
const pathnameParts = pathname.split('/')
;(locales || []).some((locale) => { ;(locales || []).some((locale) => {
if (pathname.startsWith(`/${locale}`)) { if (pathnameParts[1] === locale) {
detectedLocale = locale detectedLocale = locale
pathname = pathname.replace(new RegExp(`^/${locale}`), '') || '/' pathnameParts.splice(1, 1)
pathname = pathnameParts.join('/') || '/'
return true return true
} }
return false return false
......
...@@ -55,9 +55,13 @@ function addPathPrefix(path: string, prefix?: string) { ...@@ -55,9 +55,13 @@ function addPathPrefix(path: string, prefix?: string) {
: path : path
} }
export function addLocale(path: string, locale?: string) { export function addLocale(
path: string,
locale?: string,
defaultLocale?: string
) {
if (process.env.__NEXT_i18n_SUPPORT) { if (process.env.__NEXT_i18n_SUPPORT) {
return locale && !path.startsWith('/' + locale) return locale && locale !== defaultLocale && !path.startsWith('/' + locale)
? addPathPrefix(path, '/' + locale) ? addPathPrefix(path, '/' + locale)
: path : path
} }
...@@ -246,6 +250,7 @@ export type BaseRouter = { ...@@ -246,6 +250,7 @@ export type BaseRouter = {
basePath: string basePath: string
locale?: string locale?: string
locales?: string[] locales?: string[]
defaultLocale?: string
} }
export type NextRouter = BaseRouter & export type NextRouter = BaseRouter &
...@@ -356,6 +361,7 @@ export default class Router implements BaseRouter { ...@@ -356,6 +361,7 @@ export default class Router implements BaseRouter {
_shallow?: boolean _shallow?: boolean
locale?: string locale?: string
locales?: string[] locales?: string[]
defaultLocale?: string
static events: MittEmitter = mitt() static events: MittEmitter = mitt()
...@@ -375,6 +381,7 @@ export default class Router implements BaseRouter { ...@@ -375,6 +381,7 @@ export default class Router implements BaseRouter {
isFallback, isFallback,
locale, locale,
locales, locales,
defaultLocale,
}: { }: {
subscription: Subscription subscription: Subscription
initialProps: any initialProps: any
...@@ -387,6 +394,7 @@ export default class Router implements BaseRouter { ...@@ -387,6 +394,7 @@ export default class Router implements BaseRouter {
isFallback: boolean isFallback: boolean
locale?: string locale?: string
locales?: string[] locales?: string[]
defaultLocale?: string
} }
) { ) {
// represents the current component key // represents the current component key
...@@ -440,6 +448,7 @@ export default class Router implements BaseRouter { ...@@ -440,6 +448,7 @@ export default class Router implements BaseRouter {
if (process.env.__NEXT_i18n_SUPPORT) { if (process.env.__NEXT_i18n_SUPPORT) {
this.locale = locale this.locale = locale
this.locales = locales this.locales = locales
this.defaultLocale = defaultLocale
} }
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
...@@ -596,7 +605,7 @@ export default class Router implements BaseRouter { ...@@ -596,7 +605,7 @@ export default class Router implements BaseRouter {
this.abortComponentLoad(this._inFlightRoute) this.abortComponentLoad(this._inFlightRoute)
} }
as = addLocale(as, this.locale) as = addLocale(as, this.locale, this.defaultLocale)
const cleanedAs = delLocale( const cleanedAs = delLocale(
hasBasePath(as) ? delBasePath(as) : as, hasBasePath(as) ? delBasePath(as) : as,
this.locale this.locale
...@@ -790,7 +799,12 @@ export default class Router implements BaseRouter { ...@@ -790,7 +799,12 @@ export default class Router implements BaseRouter {
} }
Router.events.emit('beforeHistoryChange', as) Router.events.emit('beforeHistoryChange', as)
this.changeState(method, url, addLocale(as, this.locale), options) this.changeState(
method,
url,
addLocale(as, this.locale, this.defaultLocale),
options
)
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
const appComp: any = this.components['/_app'].Component const appComp: any = this.components['/_app'].Component
...@@ -960,7 +974,8 @@ export default class Router implements BaseRouter { ...@@ -960,7 +974,8 @@ export default class Router implements BaseRouter {
formatWithValidation({ pathname, query }), formatWithValidation({ pathname, query }),
delBasePath(as), delBasePath(as),
__N_SSG, __N_SSG,
this.locale this.locale,
this.defaultLocale
) )
} }
...@@ -1117,7 +1132,12 @@ export default class Router implements BaseRouter { ...@@ -1117,7 +1132,12 @@ export default class Router implements BaseRouter {
const route = removePathTrailingSlash(pathname) const route = removePathTrailingSlash(pathname)
await Promise.all([ await Promise.all([
this.pageLoader.prefetchData(url, asPath), this.pageLoader.prefetchData(
url,
asPath,
this.locale,
this.defaultLocale
),
this.pageLoader[options.priority ? 'loadPage' : 'prefetch'](route), this.pageLoader[options.priority ? 'loadPage' : 'prefetch'](route),
]) ])
} }
......
...@@ -103,6 +103,7 @@ export type NEXT_DATA = { ...@@ -103,6 +103,7 @@ export type NEXT_DATA = {
head: HeadEntry[] head: HeadEntry[]
locale?: string locale?: string
locales?: string[] locales?: string[]
defaultLocale?: string
} }
/** /**
......
...@@ -227,12 +227,35 @@ function assignDefaults(userConfig: { [key: string]: any }) { ...@@ -227,12 +227,35 @@ function assignDefaults(userConfig: { [key: string]: any }) {
throw new Error(`Specified i18n.defaultLocale should be a string`) throw new Error(`Specified i18n.defaultLocale should be a string`)
} }
if (!Array.isArray(i18n.locales)) {
throw new Error(
`Specified i18n.locales must be an array of locale strings e.g. ["en-US", "nl-NL"] received ${typeof i18n.locales}`
)
}
const invalidLocales = i18n.locales.filter(
(locale: any) => typeof locale !== 'string'
)
if (invalidLocales.length > 0) {
throw new Error(
`Specified i18n.locales contains invalid values, locales must be valid locale tags provided as strings e.g. "en-US".\n` +
`See here for list of valid language sub-tags: http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry`
)
}
if (!i18n.locales.includes(i18n.defaultLocale)) { if (!i18n.locales.includes(i18n.defaultLocale)) {
throw new Error( throw new Error(
`Specified i18n.defaultLocale should be included in i18n.locales` `Specified i18n.defaultLocale should be included in i18n.locales`
) )
} }
// make sure default Locale is at the front
i18n.locales = [
i18n.defaultLocale,
...i18n.locales.filter((locale: string) => locale !== i18n.defaultLocale),
]
const localeDetectionType = typeof i18n.locales.localeDetection const localeDetectionType = typeof i18n.locales.localeDetection
if ( if (
......
...@@ -140,6 +140,7 @@ export default class Server { ...@@ -140,6 +140,7 @@ export default class Server {
optimizeImages: boolean optimizeImages: boolean
locale?: string locale?: string
locales?: string[] locales?: string[]
defaultLocale?: string
} }
private compression?: Middleware private compression?: Middleware
private onErrorMiddleware?: ({ err }: { err: Error }) => Promise<void> private onErrorMiddleware?: ({ err }: { err: Error }) => Promise<void>
...@@ -193,6 +194,7 @@ export default class Server { ...@@ -193,6 +194,7 @@ export default class Server {
: null, : null,
optimizeImages: this.nextConfig.experimental.optimizeImages, optimizeImages: this.nextConfig.experimental.optimizeImages,
locales: this.nextConfig.experimental.i18n?.locales, locales: this.nextConfig.experimental.i18n?.locales,
defaultLocale: this.nextConfig.experimental.i18n?.defaultLocale,
} }
// Only the `publicRuntimeConfig` key is exposed to the client side // Only the `publicRuntimeConfig` key is exposed to the client side
...@@ -302,31 +304,42 @@ export default class Server { ...@@ -302,31 +304,42 @@ export default class Server {
req.url = req.url!.replace(basePath, '') || '/' req.url = req.url!.replace(basePath, '') || '/'
} }
if (i18n) { if (i18n && !parsedUrl.pathname?.startsWith('/_next')) {
// get pathname from URL with basePath stripped for locale detection // get pathname from URL with basePath stripped for locale detection
const { pathname, ...parsed } = parseUrl(req.url || '/') const { pathname, ...parsed } = parseUrl(req.url || '/')
let detectedLocale = detectLocaleCookie(req, i18n.locales) let detectedLocale = detectLocaleCookie(req, i18n.locales)
if (!detectedLocale) { if (!detectedLocale) {
detectedLocale = detectedLocale = accept.language(
accept.language(req.headers['accept-language'], i18n.locales) || req.headers['accept-language'],
i18n.defaultLocale i18n.locales
)
} }
const denormalizedPagePath = denormalizePagePath(pathname || '/')
const detectedDefaultLocale = detectedLocale === i18n.defaultLocale
const shouldStripDefaultLocale =
detectedDefaultLocale &&
denormalizedPagePath === `/${i18n.defaultLocale}`
const shouldAddLocalePrefix =
!detectedDefaultLocale && denormalizedPagePath === '/'
detectedLocale = detectedLocale || i18n.defaultLocale
if ( if (
i18n.localeDetection !== false && i18n.localeDetection !== false &&
denormalizePagePath(pathname || '/') === '/' (shouldAddLocalePrefix || shouldStripDefaultLocale)
) { ) {
res.setHeader( res.setHeader(
'Location', 'Location',
formatUrl({ formatUrl({
// make sure to include any query values when redirecting // make sure to include any query values when redirecting
...parsed, ...parsed,
pathname: `/${detectedLocale}`, pathname: shouldStripDefaultLocale ? '/' : `/${detectedLocale}`,
}) })
) )
res.statusCode = 307 res.statusCode = 307
res.end() res.end()
return
} }
// TODO: domain based locales (domain to locale mapping needs to be provided in next.config.js) // TODO: domain based locales (domain to locale mapping needs to be provided in next.config.js)
...@@ -487,21 +500,17 @@ export default class Server { ...@@ -487,21 +500,17 @@ export default class Server {
// re-create page's pathname // re-create page's pathname
let pathname = `/${params.path.join('/')}` let pathname = `/${params.path.join('/')}`
if (this.nextConfig.experimental.i18n) { const { i18n } = this.nextConfig.experimental
const localePathResult = normalizeLocalePath(
pathname, if (i18n) {
this.renderOpts.locales const localePathResult = normalizeLocalePath(pathname, i18n.locales)
) let detectedLocale = detectLocaleCookie(req, i18n.locales)
let detectedLocale = detectLocaleCookie(
req,
this.renderOpts.locales!
)
if (localePathResult.detectedLocale) { if (localePathResult.detectedLocale) {
pathname = localePathResult.pathname pathname = localePathResult.pathname
detectedLocale = localePathResult.detectedLocale detectedLocale = localePathResult.detectedLocale
} }
;(req as any)._nextLocale = detectedLocale ;(req as any)._nextLocale = detectedLocale || i18n.defaultLocale
} }
pathname = getRouteFromAssetPath(pathname, '.json') pathname = getRouteFromAssetPath(pathname, '.json')
......
...@@ -69,6 +69,7 @@ class ServerRouter implements NextRouter { ...@@ -69,6 +69,7 @@ class ServerRouter implements NextRouter {
isFallback: boolean isFallback: boolean
locale?: string locale?: string
locales?: string[] locales?: string[]
defaultLocale?: string
// TODO: Remove in the next major version, as this would mean the user is adding event listeners in server-side `render` method // TODO: Remove in the next major version, as this would mean the user is adding event listeners in server-side `render` method
static events: MittEmitter = mitt() static events: MittEmitter = mitt()
...@@ -79,7 +80,8 @@ class ServerRouter implements NextRouter { ...@@ -79,7 +80,8 @@ class ServerRouter implements NextRouter {
{ isFallback }: { isFallback: boolean }, { isFallback }: { isFallback: boolean },
basePath: string, basePath: string,
locale?: string, locale?: string,
locales?: string[] locales?: string[],
defaultLocale?: string
) { ) {
this.route = pathname.replace(/\/$/, '') || '/' this.route = pathname.replace(/\/$/, '') || '/'
this.pathname = pathname this.pathname = pathname
...@@ -89,6 +91,7 @@ class ServerRouter implements NextRouter { ...@@ -89,6 +91,7 @@ class ServerRouter implements NextRouter {
this.basePath = basePath this.basePath = basePath
this.locale = locale this.locale = locale
this.locales = locales this.locales = locales
this.defaultLocale = defaultLocale
} }
push(): any { push(): any {
noRouter() noRouter()
...@@ -164,6 +167,7 @@ export type RenderOptsPartial = { ...@@ -164,6 +167,7 @@ export type RenderOptsPartial = {
resolvedAsPath?: string resolvedAsPath?: string
locale?: string locale?: string
locales?: string[] locales?: string[]
defaultLocale?: string
} }
export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial
...@@ -203,6 +207,7 @@ function renderDocument( ...@@ -203,6 +207,7 @@ function renderDocument(
devOnlyCacheBusterQueryString, devOnlyCacheBusterQueryString,
locale, locale,
locales, locales,
defaultLocale,
}: RenderOpts & { }: RenderOpts & {
props: any props: any
docComponentsRendered: DocumentProps['docComponentsRendered'] docComponentsRendered: DocumentProps['docComponentsRendered']
...@@ -251,6 +256,7 @@ function renderDocument( ...@@ -251,6 +256,7 @@ function renderDocument(
appGip, // whether the _app has getInitialProps appGip, // whether the _app has getInitialProps
locale, locale,
locales, locales,
defaultLocale,
head: React.Children.toArray(docProps.head || []) head: React.Children.toArray(docProps.head || [])
.map((elem) => { .map((elem) => {
const { children } = elem?.props const { children } = elem?.props
...@@ -517,7 +523,8 @@ export async function renderToHTML( ...@@ -517,7 +523,8 @@ export async function renderToHTML(
}, },
basePath, basePath,
renderOpts.locale, renderOpts.locale,
renderOpts.locales renderOpts.locales,
renderOpts.defaultLocale
) )
const ctx = { const ctx = {
err, err,
......
...@@ -3,7 +3,7 @@ module.exports = { ...@@ -3,7 +3,7 @@ module.exports = {
experimental: { experimental: {
i18n: { i18n: {
locales: ['nl-NL', 'nl-BE', 'nl', 'en-US', 'en'], locales: ['nl-NL', 'nl-BE', 'nl', 'en-US', 'en'],
defaultLocale: 'en', defaultLocale: 'en-US',
}, },
}, },
} }
...@@ -167,6 +167,7 @@ export default async (appPort, path, waitHydration = true) => { ...@@ -167,6 +167,7 @@ export default async (appPort, path, waitHydration = true) => {
} }
const url = `http://${deviceIP}:${appPort}${path}` const url = `http://${deviceIP}:${appPort}${path}`
browser.initUrl = url
console.log(`\n> Loading browser with ${url}\n`) console.log(`\n> Loading browser with ${url}\n`)
await browser.get(url) await browser.get(url)
......
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