Unverified Commit 9a5a1525 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update redirect handling for locale domains (#17856)

Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent 93001511
......@@ -222,64 +222,95 @@ const nextServerlessLoader: loader.Loader = function () {
const i18n = ${i18n}
const accept = require('@hapi/accept')
const { detectLocaleCookie } = require('next/dist/next-server/lib/i18n/detect-locale-cookie')
const { detectDomainLocales } = require('next/dist/next-server/lib/i18n/detect-domain-locales')
const { detectDomainLocale } = require('next/dist/next-server/lib/i18n/detect-domain-locale')
const { normalizeLocalePath } = require('next/dist/next-server/lib/i18n/normalize-locale-path')
let locales = i18n.locales
let defaultLocale = i18n.defaultLocale
let detectedLocale = detectLocaleCookie(req, i18n.locales)
const { defaultLocale, locales } = detectDomainLocales(
req,
const detectedDomain = detectDomainLocale(
i18n.domains,
i18n.locales,
i18n.defaultLocale,
req,
)
if (detectedDomain) {
defaultLocale = detectedDomain.defaultLocale
detectedLocale = defaultLocale
}
if (!detectedLocale) {
detectedLocale = accept.language(
req.headers['accept-language'],
locales
i18n.locales
)
}
let localeDomainRedirect
const localePathResult = normalizeLocalePath(parsedUrl.pathname, i18n.locales)
if (localePathResult.detectedLocale) {
detectedLocale = localePathResult.detectedLocale
req.url = formatUrl({
...parsedUrl,
pathname: localePathResult.pathname,
})
parsedUrl.pathname = localePathResult.pathname
// check if the locale prefix matches a domain's defaultLocale
// and we're on a locale specific domain if so redirect to that domain
if (detectedDomain) {
const matchedDomain = detectDomainLocale(
i18n.domains,
undefined,
detectedLocale
)
if (matchedDomain) {
localeDomainRedirect = \`http\${
matchedDomain.http ? '' : 's'
}://\${matchedDomain.domain}\`
}
}
}
const denormalizedPagePath = denormalizePagePath(parsedUrl.pathname || '/')
const detectedDefaultLocale = !detectedLocale || detectedLocale.toLowerCase() === defaultLocale.toLowerCase()
const detectedDefaultLocale =
!detectedLocale ||
detectedLocale.toLowerCase() === defaultLocale.toLowerCase()
const shouldStripDefaultLocale =
detectedDefaultLocale &&
denormalizedPagePath.toLowerCase() === \`/\${defaultLocale.toLowerCase()}\`
denormalizedPagePath.toLowerCase() === \`/\${i18n.defaultLocale.toLowerCase()}\`
const shouldAddLocalePrefix =
!detectedDefaultLocale && denormalizedPagePath === '/'
detectedLocale = detectedLocale || defaultLocale
detectedLocale = detectedLocale || i18n.defaultLocale
if (
!fromExport &&
!nextStartMode &&
i18n.localeDetection !== false &&
(shouldAddLocalePrefix || shouldStripDefaultLocale)
(
localeDomainRedirect ||
shouldAddLocalePrefix ||
shouldStripDefaultLocale
)
) {
res.setHeader(
'Location',
formatUrl({
// make sure to include any query values when redirecting
...parsedUrl,
pathname: shouldStripDefaultLocale ? '/' : \`/\${detectedLocale}\`,
pathname:
localeDomainRedirect
? localeDomainRedirect
: shouldStripDefaultLocale
? '/'
: \`/\${detectedLocale}\`,
})
)
res.statusCode = 307
res.end()
return
}
const localePathResult = normalizeLocalePath(parsedUrl.pathname, locales)
if (localePathResult.detectedLocale) {
detectedLocale = localePathResult.detectedLocale
req.url = formatUrl({
...parsedUrl,
pathname: localePathResult.pathname,
})
parsedUrl.pathname = localePathResult.pathname
}
detectedLocale = detectedLocale || defaultLocale
`
: `
......
import { IncomingMessage } from 'http'
export function detectDomainLocales(
req: IncomingMessage,
export function detectDomainLocale(
domainItems:
| Array<{
http?: boolean
domain: string
locales: string[]
defaultLocale: string
}>
| undefined,
locales: string[],
defaultLocale: string
req?: IncomingMessage,
detectedLocale?: string
) {
let curDefaultLocale = defaultLocale
let curLocales = locales
const { host } = req.headers
let domainItem:
| {
http?: boolean
domain: string
defaultLocale: string
}
| undefined
if (host && domainItems) {
if (domainItems) {
const { host } = req?.headers || {}
// remove port from host and remove port if present
const hostname = host.split(':')[0].toLowerCase()
const hostname = host?.split(':')[0].toLowerCase()
for (const item of domainItems) {
if (hostname === item.domain.toLowerCase()) {
curDefaultLocale = item.defaultLocale
curLocales = item.locales
// remove port if present
const domainHostname = item.domain?.split(':')[0].toLowerCase()
if (
hostname === domainHostname ||
detectedLocale?.toLowerCase() === item.defaultLocale.toLowerCase()
) {
domainItem = item
break
}
}
}
return {
defaultLocale: curDefaultLocale,
locales: curLocales,
}
return domainItem
}
......@@ -238,22 +238,7 @@ function assignDefaults(userConfig: { [key: string]: any }) {
if (!item || typeof item !== 'object') return true
if (!item.defaultLocale) return true
if (!item.domain || typeof item.domain !== 'string') return true
if (!item.locales || !Array.isArray(item.locales)) return true
const invalidLocales = item.locales.filter(
(locale: string) => !i18n.locales.includes(locale)
)
if (invalidLocales.length > 0) {
console.error(
`i18n.domains item "${
item.domain
}" has the following locales (${invalidLocales.join(
', '
)}) that aren't provided in the main i18n.locales. Add them to the i18n.locales list or remove them from the domains item locales to continue.\n`
)
return true
}
return false
})
......
......@@ -79,7 +79,7 @@ import accept from '@hapi/accept'
import { normalizeLocalePath } from '../lib/i18n/normalize-locale-path'
import { detectLocaleCookie } from '../lib/i18n/detect-locale-cookie'
import * as Log from '../../build/output/log'
import { detectDomainLocales } from '../lib/i18n/detect-domain-locales'
import { detectDomainLocale } from '../lib/i18n/detect-domain-locale'
const getCustomRouteMatcher = pathMatch(true)
......@@ -306,67 +306,85 @@ export default class Server {
if (i18n && !parsedUrl.pathname?.startsWith('/_next')) {
// get pathname from URL with basePath stripped for locale detection
const { pathname, ...parsed } = parseUrl(req.url || '/')
let defaultLocale = i18n.defaultLocale
let detectedLocale = detectLocaleCookie(req, i18n.locales)
const { defaultLocale, locales } = detectDomainLocales(
req,
i18n.domains,
i18n.locales,
i18n.defaultLocale
)
const detectedDomain = detectDomainLocale(i18n.domains, req)
if (detectedDomain) {
defaultLocale = detectedDomain.defaultLocale
detectedLocale = defaultLocale
}
if (!detectedLocale) {
detectedLocale = accept.language(
req.headers['accept-language'],
locales
i18n.locales
)
}
let localeDomainRedirect: string | undefined
const localePathResult = normalizeLocalePath(pathname!, i18n.locales)
if (localePathResult.detectedLocale) {
detectedLocale = localePathResult.detectedLocale
req.url = formatUrl({
...parsed,
pathname: localePathResult.pathname,
})
parsedUrl.pathname = localePathResult.pathname
// check if the locale prefix matches a domain's defaultLocale
// and we're on a locale specific domain if so redirect to that domain
if (detectedDomain) {
const matchedDomain = detectDomainLocale(
i18n.domains,
undefined,
detectedLocale
)
if (matchedDomain) {
localeDomainRedirect = `http${matchedDomain.http ? '' : 's'}://${
matchedDomain?.domain
}`
}
}
}
const denormalizedPagePath = denormalizePagePath(pathname || '/')
const detectedDefaultLocale =
!detectedLocale ||
detectedLocale.toLowerCase() === defaultLocale.toLowerCase()
const shouldStripDefaultLocale =
detectedDefaultLocale &&
denormalizedPagePath.toLowerCase() === `/${defaultLocale.toLowerCase()}`
denormalizedPagePath.toLowerCase() ===
`/${i18n.defaultLocale.toLowerCase()}`
const shouldAddLocalePrefix =
!detectedDefaultLocale && denormalizedPagePath === '/'
detectedLocale = detectedLocale || defaultLocale
detectedLocale = detectedLocale || i18n.defaultLocale
if (
i18n.localeDetection !== false &&
(shouldAddLocalePrefix || shouldStripDefaultLocale)
(localeDomainRedirect ||
shouldAddLocalePrefix ||
shouldStripDefaultLocale)
) {
res.setHeader(
'Location',
formatUrl({
// make sure to include any query values when redirecting
...parsed,
pathname: shouldStripDefaultLocale ? '/' : `/${detectedLocale}`,
pathname: localeDomainRedirect
? localeDomainRedirect
: shouldStripDefaultLocale
? '/'
: `/${detectedLocale}`,
})
)
res.statusCode = 307
res.end()
return
}
const localePathResult = normalizeLocalePath(pathname!, locales)
if (localePathResult.detectedLocale) {
detectedLocale = localePathResult.detectedLocale
req.url = formatUrl({
...parsed,
pathname: localePathResult.pathname,
})
parsedUrl.pathname = localePathResult.pathname
}
// TODO: render with domain specific locales and defaultLocale also?
// Currently locale specific domains will have all locales populated
// under router.locales instead of only the domain specific ones
parsedUrl.query.__nextLocales = i18n.locales
// parsedUrl.query.__nextDefaultLocale = defaultLocale
parsedUrl.query.__nextLocale = detectedLocale || defaultLocale
}
......@@ -517,21 +535,15 @@ export default class Server {
if (i18n) {
const localePathResult = normalizeLocalePath(pathname, i18n.locales)
const { defaultLocale } = detectDomainLocales(
req,
i18n.domains,
i18n.locales,
i18n.defaultLocale
)
const { defaultLocale } =
detectDomainLocale(i18n.domains, req) || {}
let detectedLocale = defaultLocale
if (localePathResult.detectedLocale) {
pathname = localePathResult.pathname
detectedLocale = localePathResult.detectedLocale
}
_parsedUrl.query.__nextLocales = i18n.locales
_parsedUrl.query.__nextLocale = detectedLocale
// _parsedUrl.query.__nextDefaultLocale = defaultLocale
_parsedUrl.query.__nextLocale = detectedLocale!
}
pathname = getRouteFromAssetPath(pathname, '.json')
......@@ -1078,8 +1090,6 @@ export default class Server {
amp: query.amp,
_nextDataReq: query._nextDataReq,
__nextLocale: query.__nextLocale,
__nextLocales: query.__nextLocales,
// __nextDefaultLocale: query.__nextDefaultLocale,
}
: query),
...(params || {}),
......@@ -1151,11 +1161,10 @@ export default class Server {
delete query._nextDataReq
const locale = query.__nextLocale as string
const locales = query.__nextLocales as string[]
// const defaultLocale = query.__nextDefaultLocale as string
delete query.__nextLocale
delete query.__nextLocales
// delete query.__nextDefaultLocale
const { i18n } = this.nextConfig.experimental
const locales = i18n.locales as string[]
let previewData: string | false | object | undefined
let isPreviewMode = false
......
......@@ -414,8 +414,6 @@ export async function renderToHTML(
const isFallback = !!query.__nextFallback
delete query.__nextFallback
delete query.__nextLocale
delete query.__nextLocales
delete query.__nextDefaultLocale
const isSSG = !!getStaticProps
const isBuildTimeSSG = isSSG && renderOpts.nextExport
......
......@@ -6,13 +6,15 @@ module.exports = {
defaultLocale: 'en-US',
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-BE', 'fr-BE'],
},
{
http: true,
domain: 'example.fr',
locales: ['fr', 'fr-BE'],
defaultLocale: 'fr',
},
],
......
......@@ -132,13 +132,38 @@ function runTests(isDev) {
expect(result2.query).toEqual({})
})
it('should only handle the domain specific locales', async () => {
const checkDomainLocales = async (
domainLocales = [],
domainDefault = '',
domain = ''
) => {
it('should redirect to correct locale domain', async () => {
const checks = [
// test domain, locale prefix, redirect result
['example.be', 'nl-BE', 'http://example.be/'],
['example.be', 'fr', 'http://example.fr/'],
['example.fr', 'nl-BE', 'http://example.be/'],
['example.fr', 'fr', 'http://example.fr/'],
]
for (const check of checks) {
const [domain, localePath, location] = check
const res = await fetchViaHTTP(appPort, `/${localePath}`, undefined, {
headers: {
host: domain,
},
redirect: 'manual',
})
expect(res.status).toBe(307)
expect(res.headers.get('location')).toBe(location)
}
})
it('should handle locales with domain', async () => {
const checkDomainLocales = async (domainDefault = '', domain = '') => {
for (const locale of locales) {
// skip other domains' default locale since we redirect these
if (['fr', 'nl-BE'].includes(locale) && locale !== domainDefault) {
continue
}
const res = await fetchViaHTTP(
appPort,
`/${locale === domainDefault ? '' : locale}`,
......@@ -151,25 +176,19 @@ function runTests(isDev) {
}
)
const isDomainLocale = domainLocales.includes(locale)
expect(res.status).toBe(200)
expect(res.status).toBe(isDomainLocale ? 200 : 404)
const html = await res.text()
const $ = cheerio.load(html)
if (isDomainLocale) {
const html = await res.text()
const $ = cheerio.load(html)
expect($('html').attr('lang')).toBe(locale)
expect($('#router-locale').text()).toBe(locale)
// expect(JSON.parse($('#router-locales').text())).toEqual(domainLocales)
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
}
expect($('html').attr('lang')).toBe(locale)
expect($('#router-locale').text()).toBe(locale)
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
}
}
await checkDomainLocales(['nl-BE', 'fr-BE'], 'nl-BE', 'example.be')
await checkDomainLocales(['fr', 'fr-BE'], 'fr', 'example.fr')
await checkDomainLocales('nl-BE', 'example.be')
await checkDomainLocales('fr', 'example.fr')
})
it('should generate fallbacks with all locales', async () => {
......
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