Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure domain locales are redirected client-side #20562

Merged
merged 17 commits into from
Dec 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ export function getPageHandler(ctx: ServerlessHandlerCtx) {
locales: i18n?.locales,
locale: detectedLocale,
defaultLocale,
domainLocales: i18n?.domains,
},
options
)
Expand Down
2 changes: 2 additions & 0 deletions packages/next/client/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ const {
dynamicIds,
isFallback,
locales,
domainLocales,
} = data

let { locale, defaultLocale } = data
Expand Down Expand Up @@ -370,6 +371,7 @@ export default async (opts: { webpackHMR?: any } = {}) => {
locale,
locales,
defaultLocale,
domainLocales,
})

// call init-client middleware
Expand Down
1 change: 1 addition & 0 deletions packages/next/export/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,7 @@ Read more: https://err.sh/next.js/export-image-api`
locales: i18n?.locales,
locale: i18n?.defaultLocale,
defaultLocale: i18n?.defaultLocale,
domainLocales: i18n?.domains,
}

const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
Expand Down
63 changes: 59 additions & 4 deletions packages/next/next-server/lib/router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
isAssetError,
markAssetError,
} from '../../../client/route-loader'
import { DomainLocales } from '../../server/config'
import { denormalizePagePath } from '../../server/denormalize-page-path'
import { normalizeLocalePath } from '../i18n/normalize-locale-path'
import mitt, { MittEmitter } from '../mitt'
Expand Down Expand Up @@ -50,6 +51,13 @@ interface NextHistoryState {

type HistoryState = null | { __N: false } | ({ __N: true } & NextHistoryState)

let detectDomainLocale: typeof import('../i18n/detect-domain-locale').detectDomainLocale

if (process.env.__NEXT_I18N_SUPPORT) {
detectDomainLocale = require('../i18n/detect-domain-locale')
.detectDomainLocale
}

const basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''

function buildCancellationError() {
Expand Down Expand Up @@ -407,6 +415,7 @@ export default class Router implements BaseRouter {
locale?: string
locales?: string[]
defaultLocale?: string
domainLocales?: DomainLocales

static events: MittEmitter = mitt()

Expand All @@ -426,6 +435,7 @@ export default class Router implements BaseRouter {
locale,
locales,
defaultLocale,
domainLocales,
}: {
subscription: Subscription
initialProps: any
Expand All @@ -438,6 +448,7 @@ export default class Router implements BaseRouter {
locale?: string
locales?: string[]
defaultLocale?: string
domainLocales?: DomainLocales
}
) {
// represents the current component key
Expand Down Expand Up @@ -492,6 +503,7 @@ export default class Router implements BaseRouter {
this.locale = locale
this.locales = locales
this.defaultLocale = defaultLocale
this.domainLocales = domainLocales
}

if (typeof window !== 'undefined') {
Expand Down Expand Up @@ -666,11 +678,54 @@ export default class Router implements BaseRouter {
).pathname
)
}
let didNavigate = false

// we need to wrap this in the env check again since regenerator runtime
// moves this on its own due to the return
if (process.env.__NEXT_I18N_SUPPORT) {
// if the locale isn't configured hard navigate to show 404 page
if (!this.locales?.includes(this.locale!)) {
parsedAs.pathname = addLocale(parsedAs.pathname, this.locale)
window.location.href = formatWithValidation(parsedAs)
// this was previously a return but was removed in favor
// of better dead code elimination with regenerator runtime
didNavigate = true
}
}

const detectedDomain = detectDomainLocale(
this.domainLocales,
undefined,
this.locale
)

// we need to wrap this in the env check again since regenerator runtime
// moves this on its own due to the return
if (process.env.__NEXT_I18N_SUPPORT) {
// if we are navigating to a domain locale ensure we redirect to the
// correct domain
if (
!didNavigate &&
detectedDomain &&
self.location.hostname !== detectedDomain.domain
) {
const asNoBasePath = delBasePath(as)
window.location.href = `http${detectedDomain.http ? '' : 's'}://${
detectedDomain.domain
}${addBasePath(
`${
this.locale === detectedDomain.defaultLocale
? ''
: `/${this.locale}`
}${asNoBasePath === '/' ? '' : asNoBasePath}` || '/'
)}`
// this was previously a return but was removed in favor
// of better dead code elimination with regenerator runtime
didNavigate = true
}
}

// if the locale isn't configured hard navigate to show 404 page
if (!this.locales?.includes(this.locale!)) {
parsedAs.pathname = addLocale(parsedAs.pathname, this.locale)
window.location.href = formatWithValidation(parsedAs)
if (didNavigate) {
return new Promise(() => {})
}
}
Expand Down
2 changes: 2 additions & 0 deletions packages/next/next-server/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { ManifestItem } from '../server/load-components'
import { NextRouter } from './router/router'
import { Env } from '@next/env'
import { BuildManifest } from '../server/get-page-files'
import { DomainLocales } from '../server/config'

/**
* Types used by both next and next-server
Expand Down Expand Up @@ -101,6 +102,7 @@ export type NEXT_DATA = {
locale?: string
locales?: string[]
defaultLocale?: string
domainLocales?: DomainLocales
}

/**
Expand Down
14 changes: 8 additions & 6 deletions packages/next/next-server/server/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,18 @@ import { ImageConfig, imageConfigDefault, VALID_LOADERS } from './image-config'
const targets = ['server', 'serverless', 'experimental-serverless-trace']
const reactModes = ['legacy', 'blocking', 'concurrent']

export type DomainLocales = Array<{
http?: true
domain: string
locales?: string[]
defaultLocale: string
}>

export type NextConfig = { [key: string]: any } & {
i18n?: {
domains?: Array<{
http?: true
domain: string
locales?: string[]
defaultLocale: string
}>
locales: string[]
defaultLocale: string
domains?: DomainLocales
localeDetection?: false
} | null

Expand Down
11 changes: 9 additions & 2 deletions packages/next/next-server/server/next-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,11 @@ import {
tryGetPreviewData,
__ApiPreviewProps,
} from './api-utils'
import loadConfig, { isTargetLikeServerless, NextConfig } from './config'
import loadConfig, {
DomainLocales,
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'
Expand Down Expand Up @@ -155,6 +159,7 @@ export default class Server {
locale?: string
locales?: string[]
defaultLocale?: string
domainLocales?: DomainLocales
}
private compression?: Middleware
private onErrorMiddleware?: ({ err }: { err: Error }) => Promise<void>
Expand Down Expand Up @@ -211,6 +216,7 @@ export default class Server {
: null,
optimizeImages: this.nextConfig.experimental.optimizeImages,
optimizeCss: this.nextConfig.experimental.optimizeCss,
domainLocales: this.nextConfig.i18n?.domains,
}

// Only the `publicRuntimeConfig` key is exposed to the client side
Expand Down Expand Up @@ -1538,10 +1544,11 @@ export default class Server {
res,
'passthrough',
{
fontManifest: this.renderOpts.fontManifest,
locale,
locales,
defaultLocale,
fontManifest: this.renderOpts.fontManifest,
domainLocales: this.renderOpts.domainLocales,
}
)

Expand Down
4 changes: 4 additions & 0 deletions packages/next/next-server/server/render.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import {
getRedirectStatus,
Redirect,
} from '../../lib/load-custom-routes'
import { DomainLocales } from './config'

function noRouter() {
const message =
Expand Down Expand Up @@ -173,6 +174,7 @@ export type RenderOptsPartial = {
locale?: string
locales?: string[]
defaultLocale?: string
domainLocales?: DomainLocales
}

export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial
Expand Down Expand Up @@ -214,6 +216,7 @@ function renderDocument(
locale,
locales,
defaultLocale,
domainLocales,
}: RenderOpts & {
props: any
docComponentsRendered: DocumentProps['docComponentsRendered']
Expand Down Expand Up @@ -264,6 +267,7 @@ function renderDocument(
locale,
locales,
defaultLocale,
domainLocales,
},
buildManifest,
docComponentsRendered,
Expand Down
4 changes: 2 additions & 2 deletions test/integration/build-output/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,8 @@ describe('Build Output', () => {
expect(parseFloat(indexSize) - 266).toBeLessThanOrEqual(0)
expect(indexSize.endsWith('B')).toBe(true)

// should be no bigger than 61.8 kb
expect(parseFloat(indexFirstLoad) - 62).toBeLessThanOrEqual(0)
// should be no bigger than 62.1 kb
expect(parseFloat(indexFirstLoad) - 62.1).toBeLessThanOrEqual(0)
expect(indexFirstLoad.endsWith('kB')).toBe(true)

expect(parseFloat(err404Size) - 3.7).toBeLessThanOrEqual(0)
Expand Down
16 changes: 0 additions & 16 deletions test/integration/custom-routes-i18n/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,6 @@ module.exports = {
// 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 [
Expand Down
2 changes: 1 addition & 1 deletion test/integration/custom-routes-i18n/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const runTests = () => {
for (const [path, dest] of [
['/redirect-1', '/destination-1'],
['/en/redirect-1', '/destination-1'],
['/fr/redirect-1', 'http://example.fr/destination-1'],
['/fr/redirect-1', '/fr/destination-1'],
['/nl-NL/redirect-2', '/destination-2'],
['/fr/redirect-2', false],
]) {
Expand Down
29 changes: 19 additions & 10 deletions test/integration/i18n-support-base-path/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,31 @@ module.exports = {
// basePath: '/docs',
i18n: {
// localeDetection: false,
locales: ['nl-NL', 'nl-BE', 'nl', 'fr-BE', 'fr', 'en-US', 'en'],
locales: [
'nl-NL',
'nl-BE',
'nl',
'fr-BE',
'fr',
'en-US',
'en',
'go',
'go-BE',
'do',
'do-BE',
],
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', 'nl-NL', 'nl-BE'],
domain: 'example.do',
defaultLocale: 'do',
locales: ['do-BE'],
},
{
http: true,
domain: 'example.fr',
defaultLocale: 'fr',
locales: ['fr-BE'],
domain: 'example.com',
defaultLocale: 'go',
locales: ['go-BE'],
},
],
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export const getStaticProps = ({ params, locale, locales, defaultLocale }) => {

export const getStaticPaths = ({ locales, defaultLocale }) => {
// make sure locales were provided correctly
if (!locales || locales.length !== 7) {
if (!locales || locales.length !== 11) {
throw new Error(
'locales missing in getStaticPaths!! got: ' + JSON.stringify(locales)
)
Expand Down
27 changes: 19 additions & 8 deletions test/integration/i18n-support-base-path/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -213,20 +213,31 @@ describe('i18n Support basePath', () => {

expect(routesManifest.i18n).toEqual({
localeDetection: false,
locales: ['en-US', 'nl-NL', 'nl-BE', 'nl', 'fr-BE', 'fr', 'en'],
locales: [
'en-US',
'nl-NL',
'nl-BE',
'nl',
'fr-BE',
'fr',
'en',
'go',
'go-BE',
'do',
'do-BE',
],
defaultLocale: 'en-US',
domains: [
{
http: true,
domain: 'example.be',
defaultLocale: 'nl-BE',
locales: ['nl', 'nl-NL', 'nl-BE'],
domain: 'example.do',
defaultLocale: 'do',
locales: ['do-BE'],
},
{
http: true,
domain: 'example.fr',
defaultLocale: 'fr',
locales: ['fr-BE'],
domain: 'example.com',
defaultLocale: 'go',
locales: ['go-BE'],
},
],
})
Expand Down
Loading