Unverified Commit 1e61b69e authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add locale: false for custom-routes + i18n (#19164)

This mirrors the `basePath: false` behavior for custom-routes with `locale: false` to allow users to configure the locales manually (`locale: false`) or have the locales be handled automatically for custom-routes. 

Fixes: https://github.com/vercel/next.js/issues/18927
Fixes: https://github.com/vercel/next.js/issues/18795
parent 17a53e27
...@@ -175,3 +175,41 @@ module.exports = { ...@@ -175,3 +175,41 @@ module.exports = {
}, },
} }
``` ```
### Headers with i18n support
When leveraging [`i18n` support](/docs/advanced-features/i18n-routing.md) with headers each `source` is automatically prefixed to handle the configured `locales` unless you add `locale: false` to the header:
```js
module.exports = {
i18n: {
locales: ['en', 'fr', 'de'],
defaultLocale: 'en',
},
async headers() {
return [
{
source: '/with-locale', // automatically handles all locales
headers: [
{
key: 'x-hello',
value: 'world',
},
],
},
{
// does not handle locales automatically since locale: false is set
source: '/nl/with-locale-manual',
locale: false,
headers: [
{
key: 'x-hello',
value: 'world',
},
],
},
]
},
}
```
...@@ -120,4 +120,34 @@ module.exports = { ...@@ -120,4 +120,34 @@ module.exports = {
} }
``` ```
### Redirects with i18n support
When leveraging [`i18n` support](/docs/advanced-features/i18n-routing.md) with redirects each `source` and `destination` is automatically prefixed to handle the configured `locales` unless you add `locale: false` to the redirect:
```js
module.exports = {
i18n: {
locales: ['en', 'fr', 'de'],
defaultLocale: 'en',
},
async redirects() {
return [
{
source: '/with-locale', // automatically handles all locales
destination: '/another', // automatically passes the locale on
permanent: false,
},
{
// does not handle locales automatically since locale: false is set
source: '/nl/with-locale-manual',
destination: '/nl/another',
locale: false,
permanent: false,
},
]
},
}
```
In some rare cases, you might need to assign a custom status code for older HTTP Clients to properly redirect. In these cases, you can use the `statusCode` property instead of the `permanent` property, but not both. Note: to ensure IE11 compatibility a `Refresh` header is automatically added for the 308 status code. In some rare cases, you might need to assign a custom status code for older HTTP Clients to properly redirect. In these cases, you can use the `statusCode` property instead of the `permanent` property, but not both. Note: to ensure IE11 compatibility a `Refresh` header is automatically added for the 308 status code.
...@@ -163,3 +163,31 @@ module.exports = { ...@@ -163,3 +163,31 @@ module.exports = {
}, },
} }
``` ```
### Rewrites with i18n support
When leveraging [`i18n` support](/docs/advanced-features/i18n-routing.md) with rewrites each `source` and `destination` is automatically prefixed to handle the configured `locales` unless you add `locale: false` to the rewrite:
```js
module.exports = {
i18n: {
locales: ['en', 'fr', 'de'],
defaultLocale: 'en',
},
async rewrites() {
return [
{
source: '/with-locale', // automatically handles all locales
destination: '/another', // automatically passes the locale on
},
{
// does not handle locales automatically since locale: false is set
source: '/nl/with-locale-manual',
destination: '/nl/another',
locale: false,
},
]
},
}
```
...@@ -254,6 +254,7 @@ export default async function build( ...@@ -254,6 +254,7 @@ export default async function build(
const buildCustomRoute = ( const buildCustomRoute = (
r: { r: {
source: string source: string
locale?: false
basePath?: false basePath?: false
statusCode?: number statusCode?: number
destination?: string destination?: string
...@@ -262,7 +263,7 @@ export default async function build( ...@@ -262,7 +263,7 @@ export default async function build(
) => { ) => {
const keys: any[] = [] const keys: any[] = []
if (r.basePath !== false) { if (r.basePath !== false && (!config.i18n || r.locale === false)) {
r.source = `${config.basePath}${r.source}` r.source = `${config.basePath}${r.source}`
if (r.destination && r.destination.startsWith('/')) { if (r.destination && r.destination.startsWith('/')) {
...@@ -270,6 +271,18 @@ export default async function build( ...@@ -270,6 +271,18 @@ export default async function build(
} }
} }
if (config.i18n && r.locale !== false) {
const basePath = r.basePath !== false ? config.basePath || '' : ''
r.source = `${basePath}/:nextInternalLocale(${config.i18n.locales
.map((locale: string) => escapeStringRegexp(locale))
.join('|')})${r.source}`
if (r.destination && r.destination?.startsWith('/')) {
r.destination = `${basePath}/:nextInternalLocale${r.destination}`
}
}
const routeRegex = pathToRegexp(r.source, keys, { const routeRegex = pathToRegexp(r.source, keys, {
strict: true, strict: true,
sensitive: false, sensitive: false,
......
...@@ -191,8 +191,7 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -191,8 +191,7 @@ const nextServerlessLoader: loader.Loader = function () {
rewrite.destination, rewrite.destination,
params, params,
parsedUrl.query, parsedUrl.query,
true, true
"${basePath}"
) )
Object.assign(parsedUrl.query, parsedDestination.query) Object.assign(parsedUrl.query, parsedDestination.query)
...@@ -200,13 +199,43 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -200,13 +199,43 @@ const nextServerlessLoader: loader.Loader = function () {
Object.assign(parsedUrl, parsedDestination) Object.assign(parsedUrl, parsedDestination)
if (parsedUrl.pathname === '${page}'){ let fsPathname = parsedUrl.pathname
${
basePath
? `
fsPathname = fsPathname.replace(
new RegExp('^${basePath}'),
''
) || '/'
`
: ''
}
${
i18n
? `
const destLocalePathResult = normalizeLocalePath(
fsPathname,
i18n.locales
)
fsPathname = destLocalePathResult.pathname
parsedUrl.query.nextInternalLocale = (
destLocalePathResult.detectedLocale ||
params.nextInternalLocale
)
`
: ''
}
if (fsPathname === '${page}'){
break break
} }
${ ${
pageIsDynamicRoute pageIsDynamicRoute
? ` ? `
const dynamicParams = dynamicRouteMatcher(parsedUrl.pathname);\ const dynamicParams = dynamicRouteMatcher(fsPathname);\
if (dynamicParams) { if (dynamicParams) {
parsedUrl.query = { parsedUrl.query = {
...parsedUrl.query, ...parsedUrl.query,
...@@ -235,12 +264,10 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -235,12 +264,10 @@ const nextServerlessLoader: loader.Loader = function () {
const handleLocale = i18nEnabled const handleLocale = i18nEnabled
? ` ? `
// get pathname from URL with basePath stripped for locale detection // get pathname from URL with basePath stripped for locale detection
const i18n = ${i18n}
const accept = require('@hapi/accept') const accept = require('@hapi/accept')
const cookie = require('next/dist/compiled/cookie') const cookie = require('next/dist/compiled/cookie')
const { detectLocaleCookie } = require('next/dist/next-server/lib/i18n/detect-locale-cookie') const { detectLocaleCookie } = require('next/dist/next-server/lib/i18n/detect-locale-cookie')
const { detectDomainLocale } = require('next/dist/next-server/lib/i18n/detect-domain-locale') 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 locales = i18n.locales
let defaultLocale = i18n.defaultLocale let defaultLocale = i18n.defaultLocale
let detectedLocale = detectLocaleCookie(req, i18n.locales) let detectedLocale = detectLocaleCookie(req, i18n.locales)
...@@ -400,6 +427,9 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -400,6 +427,9 @@ const nextServerlessLoader: loader.Loader = function () {
${dynamicRouteImports} ${dynamicRouteImports}
const { parse: parseUrl } = require('url') const { parse: parseUrl } = require('url')
const { apiResolver } = require('next/dist/next-server/server/api-utils') const { apiResolver } = require('next/dist/next-server/server/api-utils')
const { normalizeLocalePath } = require('next/dist/next-server/lib/i18n/normalize-locale-path')
const i18n = ${i18n || '{}'}
${rewriteImports} ${rewriteImports}
${dynamicRouteMatcher} ${dynamicRouteMatcher}
...@@ -416,6 +446,12 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -416,6 +446,12 @@ const nextServerlessLoader: loader.Loader = function () {
// to ensure we are using the correct values // to ensure we are using the correct values
const trustQuery = req.headers['${vercelHeader}'] const trustQuery = req.headers['${vercelHeader}']
const parsedUrl = handleRewrites(parseUrl(req.url, true)) const parsedUrl = handleRewrites(parseUrl(req.url, true))
if (parsedUrl.query.nextInternalLocale) {
detectedLocale = parsedUrl.query.nextInternalLocale
delete parsedUrl.query.nextInternalLocale
}
let hasValidParams = true let hasValidParams = true
${normalizeDynamicRouteParams} ${normalizeDynamicRouteParams}
...@@ -482,6 +518,8 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -482,6 +518,8 @@ const nextServerlessLoader: loader.Loader = function () {
const {PERMANENT_REDIRECT_STATUS} = require('next/dist/next-server/lib/constants') const {PERMANENT_REDIRECT_STATUS} = require('next/dist/next-server/lib/constants')
const buildManifest = require('${buildManifest}'); const buildManifest = require('${buildManifest}');
const reactLoadableManifest = require('${reactLoadableManifest}'); const reactLoadableManifest = require('${reactLoadableManifest}');
const { normalizeLocalePath } = require('next/dist/next-server/lib/i18n/normalize-locale-path')
const i18n = ${i18n || '{}'}
const appMod = require('${absoluteAppPath}') const appMod = require('${absoluteAppPath}')
let App = appMod.default || appMod.then && appMod.then(mod => mod.default); let App = appMod.default || appMod.then && appMod.then(mod => mod.default);
...@@ -606,6 +644,11 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -606,6 +644,11 @@ const nextServerlessLoader: loader.Loader = function () {
${handleLocale} ${handleLocale}
if (parsedUrl.query.nextInternalLocale) {
detectedLocale = parsedUrl.query.nextInternalLocale
delete parsedUrl.query.nextInternalLocale
}
const renderOpts = Object.assign( const renderOpts = Object.assign(
{ {
Component, Component,
......
...@@ -9,11 +9,13 @@ export type Rewrite = { ...@@ -9,11 +9,13 @@ export type Rewrite = {
source: string source: string
destination: string destination: string
basePath?: false basePath?: false
locale?: false
} }
export type Header = { export type Header = {
source: string source: string
basePath?: false basePath?: false
locale?: false
headers: Array<{ key: string; value: string }> headers: Array<{ key: string; value: string }>
} }
...@@ -21,8 +23,6 @@ export type Header = { ...@@ -21,8 +23,6 @@ export type Header = {
export type Redirect = Rewrite & { export type Redirect = Rewrite & {
statusCode?: number statusCode?: number
permanent?: boolean permanent?: boolean
destination: string
basePath?: false
} }
export const allowedStatusCodes = new Set([301, 302, 303, 307, 308]) export const allowedStatusCodes = new Set([301, 302, 303, 307, 308])
...@@ -157,10 +157,11 @@ function checkCustomRoutes( ...@@ -157,10 +157,11 @@ function checkCustomRoutes(
'source', 'source',
'destination', 'destination',
'basePath', 'basePath',
'locale',
...(isRedirect ? ['statusCode', 'permanent'] : []), ...(isRedirect ? ['statusCode', 'permanent'] : []),
]) ])
} else { } else {
allowedKeys = new Set(['source', 'headers', 'basePath']) allowedKeys = new Set(['source', 'headers', 'basePath', 'locale'])
} }
for (const route of routes) { for (const route of routes) {
...@@ -201,6 +202,10 @@ function checkCustomRoutes( ...@@ -201,6 +202,10 @@ function checkCustomRoutes(
invalidParts.push('`basePath` must be undefined or false') invalidParts.push('`basePath` must be undefined or false')
} }
if (typeof route.locale !== 'undefined' && route.locale !== false) {
invalidParts.push('`locale` must be undefined or true')
}
if (!route.source) { if (!route.source) {
invalidParts.push('`source` is missing') invalidParts.push('`source` is missing')
} else if (typeof route.source !== 'string') { } else if (typeof route.source !== 'string') {
...@@ -386,11 +391,13 @@ export default async function loadCustomRoutes( ...@@ -386,11 +391,13 @@ export default async function loadCustomRoutes(
source: '/:file((?:[^/]+/)*[^/]+\\.\\w+)/', source: '/:file((?:[^/]+/)*[^/]+\\.\\w+)/',
destination: '/:file', destination: '/:file',
permanent: true, permanent: true,
locale: config.i18n ? false : undefined,
}, },
{ {
source: '/:notfile((?:[^/]+/)*[^/\\.]+)', source: '/:notfile((?:[^/]+/)*[^/\\.]+)',
destination: '/:notfile/', destination: '/:notfile/',
permanent: true, permanent: true,
locale: config.i18n ? false : undefined,
} }
) )
if (config.basePath) { if (config.basePath) {
...@@ -399,6 +406,7 @@ export default async function loadCustomRoutes( ...@@ -399,6 +406,7 @@ export default async function loadCustomRoutes(
destination: config.basePath + '/', destination: config.basePath + '/',
permanent: true, permanent: true,
basePath: false, basePath: false,
locale: config.i18n ? false : undefined,
}) })
} }
} else { } else {
...@@ -406,6 +414,7 @@ export default async function loadCustomRoutes( ...@@ -406,6 +414,7 @@ export default async function loadCustomRoutes(
source: '/:path+/', source: '/:path+/',
destination: '/:path+', destination: '/:path+',
permanent: true, permanent: true,
locale: config.i18n ? false : undefined,
}) })
if (config.basePath) { if (config.basePath) {
redirects.unshift({ redirects.unshift({
...@@ -413,6 +422,7 @@ export default async function loadCustomRoutes( ...@@ -413,6 +422,7 @@ export default async function loadCustomRoutes(
destination: config.basePath, destination: config.basePath,
permanent: true, permanent: true,
basePath: false, basePath: false,
locale: config.i18n ? false : undefined,
}) })
} }
} }
......
...@@ -58,6 +58,7 @@ export default function prepareDestination( ...@@ -58,6 +58,7 @@ export default function prepareDestination(
// clone query so we don't modify the original // clone query so we don't modify the original
query = Object.assign({}, query) query = Object.assign({}, query)
const hadLocale = query.__nextLocale
delete query.__nextLocale delete query.__nextLocale
delete query.__nextDefaultLocale delete query.__nextDefaultLocale
...@@ -121,7 +122,12 @@ export default function prepareDestination( ...@@ -121,7 +122,12 @@ export default function prepareDestination(
// add path params to query if it's not a redirect and not // add path params to query if it's not a redirect and not
// already defined in destination query or path // already defined in destination query or path
const paramKeys = Object.keys(params) let paramKeys = Object.keys(params)
// remove internal param for i18n
if (hadLocale) {
paramKeys = paramKeys.filter((name) => name !== 'nextInternalLocale')
}
if ( if (
appendParamsToQuery && appendParamsToQuery &&
...@@ -144,7 +150,7 @@ export default function prepareDestination( ...@@ -144,7 +150,7 @@ export default function prepareDestination(
const [pathname, hash] = newUrl.split('#') const [pathname, hash] = newUrl.split('#')
parsedDestination.pathname = pathname parsedDestination.pathname = pathname
parsedDestination.hash = `${hash ? '#' : ''}${hash || ''}` parsedDestination.hash = `${hash ? '#' : ''}${hash || ''}`
delete parsedDestination.search delete (parsedDestination as any).search
} catch (err) { } catch (err) {
if (err.message.match(/Expected .*? to not repeat, but got an array/)) { if (err.message.match(/Expected .*? to not repeat, but got an array/)) {
throw new Error( throw new Error(
......
...@@ -84,6 +84,7 @@ import * as Log from '../../build/output/log' ...@@ -84,6 +84,7 @@ import * as Log from '../../build/output/log'
import { imageOptimizer } from './image-optimizer' import { imageOptimizer } from './image-optimizer'
import { detectDomainLocale } from '../lib/i18n/detect-domain-locale' import { detectDomainLocale } from '../lib/i18n/detect-domain-locale'
import cookie from 'next/dist/compiled/cookie' import cookie from 'next/dist/compiled/cookie'
import escapeStringRegexp from 'next/dist/compiled/escape-string-regexp'
const getCustomRouteMatcher = pathMatch(true) const getCustomRouteMatcher = pathMatch(true)
...@@ -504,6 +505,7 @@ export default class Server { ...@@ -504,6 +505,7 @@ export default class Server {
pageChecker: PageChecker pageChecker: PageChecker
useFileSystemPublicRoutes: boolean useFileSystemPublicRoutes: boolean
dynamicRoutes: DynamicRoutes | undefined dynamicRoutes: DynamicRoutes | undefined
locales: string[]
} { } {
const server: Server = this const server: Server = this
const publicRoutes = fs.existsSync(this.publicDir) const publicRoutes = fs.existsSync(this.publicDir)
...@@ -658,14 +660,41 @@ export default class Server { ...@@ -658,14 +660,41 @@ export default class Server {
: '' : ''
} }
const getCustomRoute = (r: Rewrite | Redirect | Header, type: RouteType) => const getCustomRouteLocalePrefix = (r: {
({ locale?: false
destination?: string
}) => {
const { i18n } = this.nextConfig
if (!i18n || r.locale === false || !this.renderOpts.dev) return ''
if (r.destination && r.destination.startsWith('/')) {
r.destination = `/:nextInternalLocale${r.destination}`
}
return `/:nextInternalLocale(${i18n.locales
.map((locale: string) => escapeStringRegexp(locale))
.join('|')})`
}
const getCustomRoute = (
r: Rewrite | Redirect | Header,
type: RouteType
) => {
const match = getCustomRouteMatcher(
`${getCustomRouteBasePath(r)}${getCustomRouteLocalePrefix(r)}${
r.source
}`
)
return {
...r, ...r,
type, type,
match: getCustomRouteMatcher(`${getCustomRouteBasePath(r)}${r.source}`), match,
name: type, name: type,
fn: async (_req, _res, _params, _parsedUrl) => ({ finished: false }), fn: async (_req, _res, _params, _parsedUrl) => ({ finished: false }),
} as Route & Rewrite & Header) } as Route & Rewrite & Header
}
// Headers come very first // Headers come very first
const headers = this.customRoutes.headers.map((r) => { const headers = this.customRoutes.headers.map((r) => {
...@@ -810,6 +839,18 @@ export default class Server { ...@@ -810,6 +839,18 @@ export default class Server {
// next.js core assumes page path without trailing slash // next.js core assumes page path without trailing slash
pathname = removePathTrailingSlash(pathname) pathname = removePathTrailingSlash(pathname)
if (this.nextConfig.i18n) {
const localePathResult = normalizeLocalePath(
pathname,
this.nextConfig.i18n?.locales
)
if (localePathResult.detectedLocale) {
pathname = localePathResult.pathname
parsedUrl.query.__nextLocale = localePathResult.detectedLocale
}
}
if (params?.path?.[0] === 'api') { if (params?.path?.[0] === 'api') {
const handled = await this.handleApiRequest( const handled = await this.handleApiRequest(
req as NextApiRequest, req as NextApiRequest,
...@@ -845,6 +886,7 @@ export default class Server { ...@@ -845,6 +886,7 @@ export default class Server {
dynamicRoutes: this.dynamicRoutes, dynamicRoutes: this.dynamicRoutes,
basePath: this.nextConfig.basePath, basePath: this.nextConfig.basePath,
pageChecker: this.hasPage.bind(this), pageChecker: this.hasPage.bind(this),
locales: this.nextConfig.i18n?.locales,
} }
} }
......
...@@ -3,6 +3,7 @@ import { UrlWithParsedQuery } from 'url' ...@@ -3,6 +3,7 @@ import { UrlWithParsedQuery } from 'url'
import pathMatch from '../lib/router/utils/path-match' import pathMatch from '../lib/router/utils/path-match'
import { removePathTrailingSlash } from '../../client/normalize-trailing-slash' import { removePathTrailingSlash } from '../../client/normalize-trailing-slash'
import { normalizeLocalePath } from '../lib/i18n/normalize-locale-path'
export const route = pathMatch() export const route = pathMatch()
...@@ -52,6 +53,7 @@ export default class Router { ...@@ -52,6 +53,7 @@ export default class Router {
pageChecker: PageChecker pageChecker: PageChecker
dynamicRoutes: DynamicRoutes dynamicRoutes: DynamicRoutes
useFileSystemPublicRoutes: boolean useFileSystemPublicRoutes: boolean
locales: string[]
constructor({ constructor({
basePath = '', basePath = '',
...@@ -63,6 +65,7 @@ export default class Router { ...@@ -63,6 +65,7 @@ export default class Router {
dynamicRoutes = [], dynamicRoutes = [],
pageChecker, pageChecker,
useFileSystemPublicRoutes, useFileSystemPublicRoutes,
locales = [],
}: { }: {
basePath: string basePath: string
headers: Route[] headers: Route[]
...@@ -73,6 +76,7 @@ export default class Router { ...@@ -73,6 +76,7 @@ export default class Router {
dynamicRoutes: DynamicRoutes | undefined dynamicRoutes: DynamicRoutes | undefined
pageChecker: PageChecker pageChecker: PageChecker
useFileSystemPublicRoutes: boolean useFileSystemPublicRoutes: boolean
locales: string[]
}) { }) {
this.basePath = basePath this.basePath = basePath
this.headers = headers this.headers = headers
...@@ -83,6 +87,7 @@ export default class Router { ...@@ -83,6 +87,7 @@ export default class Router {
this.catchAllRoute = catchAllRoute this.catchAllRoute = catchAllRoute
this.dynamicRoutes = dynamicRoutes this.dynamicRoutes = dynamicRoutes
this.useFileSystemPublicRoutes = useFileSystemPublicRoutes this.useFileSystemPublicRoutes = useFileSystemPublicRoutes
this.locales = locales
} }
setDynamicRoutes(routes: DynamicRoutes = []) { setDynamicRoutes(routes: DynamicRoutes = []) {
...@@ -101,6 +106,8 @@ export default class Router { ...@@ -101,6 +106,8 @@ export default class Router {
// memoize page check calls so we don't duplicate checks for pages // memoize page check calls so we don't duplicate checks for pages
const pageChecks: { [name: string]: Promise<boolean> } = {} const pageChecks: { [name: string]: Promise<boolean> } = {}
const memoizedPageChecker = async (p: string): Promise<boolean> => { const memoizedPageChecker = async (p: string): Promise<boolean> => {
p = normalizeLocalePath(p, this.locales).pathname
if (pageChecks[p]) { if (pageChecks[p]) {
return pageChecks[p] return pageChecks[p]
} }
...@@ -178,11 +185,7 @@ export default class Router { ...@@ -178,11 +185,7 @@ export default class Router {
} }
// re-add locale for custom-routes to allow matching against // re-add locale for custom-routes to allow matching against
if ( if (isCustomRoute && parsedUrl.query.__nextLocale) {
isCustomRoute &&
(req as any).__nextStrippedLocale &&
parsedUrl.query.__nextLocale
) {
if (keepBasePath) { if (keepBasePath) {
currentPathname = replaceBasePath(this.basePath, currentPathname!) currentPathname = replaceBasePath(this.basePath, currentPathname!)
} }
......
...@@ -25,17 +25,19 @@ module.exports = { ...@@ -25,17 +25,19 @@ module.exports = {
async redirects() { async redirects() {
return [ return [
{ {
source: '/en-US/redirect', source: '/en-US/redirect-1',
destination: '/somewhere-else', destination: '/somewhere-else',
permanent: false, permanent: false,
locale: false,
}, },
{ {
source: '/nl/redirect', source: '/nl/redirect-2',
destination: '/somewhere-else', destination: '/somewhere-else',
permanent: false, permanent: false,
locale: false,
}, },
{ {
source: '/redirect', source: '/redirect-3',
destination: '/somewhere-else', destination: '/somewhere-else',
permanent: false, permanent: false,
}, },
...@@ -44,23 +46,35 @@ module.exports = { ...@@ -44,23 +46,35 @@ module.exports = {
async rewrites() { async rewrites() {
return [ return [
{ {
source: '/en-US/rewrite', source: '/en-US/rewrite-1',
destination: '/another', destination: '/another',
locale: false,
}, },
{ {
source: '/nl/rewrite', source: '/nl/rewrite-2',
destination: '/another', destination: '/nl/another',
locale: false,
},
{
source: '/fr/rewrite-3',
destination: '/nl/another',
locale: false,
}, },
{ {
source: '/rewrite', source: '/rewrite-4',
destination: '/another', destination: '/another',
}, },
{
source: '/rewrite-5',
destination: 'http://localhost:__EXTERNAL_PORT__',
},
] ]
}, },
async headers() { async headers() {
return [ return [
{ {
source: '/en-US/add-header', source: '/en-US/add-header-1',
locale: false,
headers: [ headers: [
{ {
key: 'x-hello', key: 'x-hello',
...@@ -69,7 +83,8 @@ module.exports = { ...@@ -69,7 +83,8 @@ module.exports = {
], ],
}, },
{ {
source: '/nl/add-header', source: '/nl/add-header-2',
locale: false,
headers: [ headers: [
{ {
key: 'x-hello', key: 'x-hello',
...@@ -78,7 +93,7 @@ module.exports = { ...@@ -78,7 +93,7 @@ module.exports = {
], ],
}, },
{ {
source: '/add-header', source: '/add-header-3',
headers: [ headers: [
{ {
key: 'x-hello', key: 'x-hello',
......
...@@ -21,7 +21,20 @@ const ctx = { ...@@ -21,7 +21,20 @@ const ctx = {
appDir, appDir,
} }
describe('i18n Support', () => { describe('i18n Support basePath', () => {
beforeAll(async () => {
ctx.externalPort = await findPort()
ctx.externalApp = http.createServer((req, res) => {
res.statusCode = 200
res.end(JSON.stringify({ url: req.url, external: true }))
})
await new Promise((resolve, reject) => {
ctx.externalApp.listen(ctx.externalPort, (err) =>
err ? reject(err) : resolve()
)
})
})
describe('dev mode', () => { describe('dev mode', () => {
const curCtx = { const curCtx = {
...ctx, ...ctx,
...@@ -29,6 +42,7 @@ describe('i18n Support', () => { ...@@ -29,6 +42,7 @@ describe('i18n Support', () => {
} }
beforeAll(async () => { beforeAll(async () => {
nextConfig.replace('// basePath', 'basePath') nextConfig.replace('// basePath', 'basePath')
nextConfig.replace(/__EXTERNAL_PORT__/g, ctx.externalPort)
await fs.remove(join(appDir, '.next')) await fs.remove(join(appDir, '.next'))
curCtx.appPort = await findPort() curCtx.appPort = await findPort()
curCtx.app = await launchApp(appDir, curCtx.appPort) curCtx.app = await launchApp(appDir, curCtx.appPort)
...@@ -44,6 +58,7 @@ describe('i18n Support', () => { ...@@ -44,6 +58,7 @@ describe('i18n Support', () => {
describe('production mode', () => { describe('production mode', () => {
beforeAll(async () => { beforeAll(async () => {
nextConfig.replace('// basePath', 'basePath') nextConfig.replace('// basePath', 'basePath')
nextConfig.replace(/__EXTERNAL_PORT__/g, ctx.externalPort)
await fs.remove(join(appDir, '.next')) await fs.remove(join(appDir, '.next'))
await nextBuild(appDir) await nextBuild(appDir)
ctx.appPort = await findPort() ctx.appPort = await findPort()
...@@ -64,6 +79,7 @@ describe('i18n Support', () => { ...@@ -64,6 +79,7 @@ describe('i18n Support', () => {
await fs.remove(join(appDir, '.next')) await fs.remove(join(appDir, '.next'))
nextConfig.replace('// target', 'target') nextConfig.replace('// target', 'target')
nextConfig.replace('// basePath', 'basePath') nextConfig.replace('// basePath', 'basePath')
nextConfig.replace(/__EXTERNAL_PORT__/g, ctx.externalPort)
await nextBuild(appDir) await nextBuild(appDir)
ctx.appPort = await findPort() ctx.appPort = await findPort()
...@@ -118,6 +134,60 @@ describe('i18n Support', () => { ...@@ -118,6 +134,60 @@ describe('i18n Support', () => {
}) })
}) })
it('should resolve rewrites correctly', async () => {
const serverFile = getPageFileFromPagesManifest(appDir, '/another')
const appPort = await findPort()
const mod = require(join(appDir, '.next/serverless', serverFile))
const server = http.createServer(async (req, res) => {
try {
await mod.render(req, res)
} catch (err) {
res.statusCode = 500
res.end('internal err')
}
})
await new Promise((resolve, reject) => {
server.listen(appPort, (err) => (err ? reject(err) : resolve()))
})
console.log('listening on', appPort)
const requests = await Promise.all(
[
'/en-US/rewrite-1',
'/nl/rewrite-2',
'/fr/rewrite-3',
'/en-US/rewrite-4',
'/fr/rewrite-4',
].map((path) =>
fetchViaHTTP(appPort, `${ctx.basePath}${path}`, undefined, {
redirect: 'manual',
})
)
)
server.close()
const checks = [
['en-US', '/rewrite-1'],
['nl', '/rewrite-2'],
['nl', '/rewrite-3'],
['en-US', '/rewrite-4'],
['fr', '/rewrite-4'],
]
for (let i = 0; i < requests.length; i++) {
const res = requests[i]
const [locale, asPath] = checks[i]
const $ = cheerio.load(await res.text())
expect($('html').attr('lang')).toBe(locale)
expect($('#router-locale').text()).toBe(locale)
expect($('#router-pathname').text()).toBe('/another')
expect($('#router-as-path').text()).toBe(asPath)
}
})
runTests(ctx) runTests(ctx)
}) })
......
...@@ -25,17 +25,19 @@ module.exports = { ...@@ -25,17 +25,19 @@ module.exports = {
async redirects() { async redirects() {
return [ return [
{ {
source: '/en-US/redirect', source: '/en-US/redirect-1',
destination: '/somewhere-else', destination: '/somewhere-else',
permanent: false, permanent: false,
locale: false,
}, },
{ {
source: '/nl/redirect', source: '/nl/redirect-2',
destination: '/somewhere-else', destination: '/somewhere-else',
permanent: false, permanent: false,
locale: false,
}, },
{ {
source: '/redirect', source: '/redirect-3',
destination: '/somewhere-else', destination: '/somewhere-else',
permanent: false, permanent: false,
}, },
...@@ -44,23 +46,35 @@ module.exports = { ...@@ -44,23 +46,35 @@ module.exports = {
async rewrites() { async rewrites() {
return [ return [
{ {
source: '/en-US/rewrite', source: '/en-US/rewrite-1',
destination: '/another', destination: '/another',
locale: false,
}, },
{ {
source: '/nl/rewrite', source: '/nl/rewrite-2',
destination: '/another', destination: '/nl/another',
locale: false,
},
{
source: '/fr/rewrite-3',
destination: '/nl/another',
locale: false,
}, },
{ {
source: '/rewrite', source: '/rewrite-4',
destination: '/another', destination: '/another',
}, },
{
source: '/rewrite-5',
destination: 'http://localhost:__EXTERNAL_PORT__',
},
] ]
}, },
async headers() { async headers() {
return [ return [
{ {
source: '/en-US/add-header', source: '/en-US/add-header-1',
locale: false,
headers: [ headers: [
{ {
key: 'x-hello', key: 'x-hello',
...@@ -69,7 +83,8 @@ module.exports = { ...@@ -69,7 +83,8 @@ module.exports = {
], ],
}, },
{ {
source: '/nl/add-header', source: '/nl/add-header-2',
locale: false,
headers: [ headers: [
{ {
key: 'x-hello', key: 'x-hello',
...@@ -78,7 +93,7 @@ module.exports = { ...@@ -78,7 +93,7 @@ module.exports = {
], ],
}, },
{ {
source: '/add-header', source: '/add-header-3',
headers: [ headers: [
{ {
key: 'x-hello', key: 'x-hello',
......
export default (req, res) => {
res.json({ hello: true, query: req.query })
}
export default (req, res) => {
res.json({ post: true, query: req.query })
}
const http = require('http')
const mod = require('./.next/serverless/pages/another')
const server = http.createServer(async (req, res) => {
try {
await mod.render(req, res)
} catch (err) {
console.error(err)
res.statusCode = 500
res.end('internal error')
}
})
server.listen(3000, () => console.log('listening'))
...@@ -22,6 +22,20 @@ const ctx = { ...@@ -22,6 +22,20 @@ const ctx = {
} }
describe('i18n Support', () => { describe('i18n Support', () => {
beforeAll(async () => {
ctx.externalPort = await findPort()
ctx.externalApp = http.createServer((req, res) => {
res.statusCode = 200
res.end(JSON.stringify({ url: req.url, external: true }))
})
await new Promise((resolve, reject) => {
ctx.externalApp.listen(ctx.externalPort, (err) =>
err ? reject(err) : resolve()
)
})
})
afterAll(() => ctx.externalApp.close())
describe('dev mode', () => { describe('dev mode', () => {
const curCtx = { const curCtx = {
...ctx, ...ctx,
...@@ -29,11 +43,13 @@ describe('i18n Support', () => { ...@@ -29,11 +43,13 @@ describe('i18n Support', () => {
} }
beforeAll(async () => { beforeAll(async () => {
await fs.remove(join(appDir, '.next')) await fs.remove(join(appDir, '.next'))
nextConfig.replace(/__EXTERNAL_PORT__/g, ctx.externalPort)
curCtx.appPort = await findPort() curCtx.appPort = await findPort()
curCtx.app = await launchApp(appDir, curCtx.appPort) curCtx.app = await launchApp(appDir, curCtx.appPort)
}) })
afterAll(async () => { afterAll(async () => {
await killApp(curCtx.app) await killApp(curCtx.app)
nextConfig.restore()
}) })
runTests(curCtx) runTests(curCtx)
...@@ -42,13 +58,17 @@ describe('i18n Support', () => { ...@@ -42,13 +58,17 @@ describe('i18n Support', () => {
describe('production mode', () => { describe('production mode', () => {
beforeAll(async () => { beforeAll(async () => {
await fs.remove(join(appDir, '.next')) await fs.remove(join(appDir, '.next'))
nextConfig.replace(/__EXTERNAL_PORT__/g, ctx.externalPort)
await nextBuild(appDir) await nextBuild(appDir)
ctx.appPort = await findPort() ctx.appPort = await findPort()
ctx.app = await nextStart(appDir, ctx.appPort) ctx.app = await nextStart(appDir, ctx.appPort)
ctx.buildPagesDir = join(appDir, '.next/server/pages') ctx.buildPagesDir = join(appDir, '.next/server/pages')
ctx.buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8') ctx.buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
}) })
afterAll(() => killApp(ctx.app)) afterAll(async () => {
await killApp(ctx.app)
nextConfig.restore()
})
runTests(ctx) runTests(ctx)
}) })
...@@ -57,6 +77,7 @@ describe('i18n Support', () => { ...@@ -57,6 +77,7 @@ describe('i18n Support', () => {
beforeAll(async () => { beforeAll(async () => {
await fs.remove(join(appDir, '.next')) await fs.remove(join(appDir, '.next'))
nextConfig.replace('// target', 'target') nextConfig.replace('// target', 'target')
nextConfig.replace(/__EXTERNAL_PORT__/g, ctx.externalPort)
await nextBuild(appDir) await nextBuild(appDir)
ctx.appPort = await findPort() ctx.appPort = await findPort()
...@@ -111,6 +132,60 @@ describe('i18n Support', () => { ...@@ -111,6 +132,60 @@ describe('i18n Support', () => {
}) })
}) })
it('should resolve rewrites correctly', async () => {
const serverFile = getPageFileFromPagesManifest(appDir, '/another')
const appPort = await findPort()
const mod = require(join(appDir, '.next/serverless', serverFile))
const server = http.createServer(async (req, res) => {
try {
await mod.render(req, res)
} catch (err) {
res.statusCode = 500
res.end('internal err')
}
})
await new Promise((resolve, reject) => {
server.listen(appPort, (err) => (err ? reject(err) : resolve()))
})
console.log('listening on', appPort)
const requests = await Promise.all(
[
'/en-US/rewrite-1',
'/nl/rewrite-2',
'/fr/rewrite-3',
'/en-US/rewrite-4',
'/fr/rewrite-4',
].map((path) =>
fetchViaHTTP(appPort, `${ctx.basePath}${path}`, undefined, {
redirect: 'manual',
})
)
)
server.close()
const checks = [
['en-US', '/rewrite-1'],
['nl', '/rewrite-2'],
['nl', '/rewrite-3'],
['en-US', '/rewrite-4'],
['fr', '/rewrite-4'],
]
for (let i = 0; i < requests.length; i++) {
const res = requests[i]
const [locale, asPath] = checks[i]
const $ = cheerio.load(await res.text())
expect($('html').attr('lang')).toBe(locale)
expect($('#router-locale').text()).toBe(locale)
expect($('#router-pathname').text()).toBe('/another')
expect($('#router-as-path').text()).toBe(asPath)
}
})
runTests(ctx) runTests(ctx)
}) })
......
...@@ -309,7 +309,15 @@ export function runTests(ctx) { ...@@ -309,7 +309,15 @@ export function runTests(ctx) {
}) })
it('should apply redirects correctly', async () => { it('should apply redirects correctly', async () => {
for (const path of ['/redirect', '/en-US/redirect', '/nl/redirect']) { for (const [path, shouldRedirect, locale] of [
['/en-US/redirect-1', true],
['/en/redirect-1', false],
['/nl/redirect-2', true],
['/fr/redirect-2', false],
['/redirect-3', true, '/en-US'],
['/en/redirect-3', true, '/en'],
['/nl-NL/redirect-3', true, '/nl-NL'],
]) {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
ctx.appPort, ctx.appPort,
`${ctx.basePath}${path}`, `${ctx.basePath}${path}`,
...@@ -318,16 +326,29 @@ export function runTests(ctx) { ...@@ -318,16 +326,29 @@ export function runTests(ctx) {
redirect: 'manual', redirect: 'manual',
} }
) )
expect(res.status).toBe(307)
expect(res.status).toBe(shouldRedirect ? 307 : 404)
if (shouldRedirect) {
const parsed = url.parse(res.headers.get('location'), true) const parsed = url.parse(res.headers.get('location'), true)
expect(parsed.pathname).toBe(`${ctx.basePath}/somewhere-else`) expect(parsed.pathname).toBe(
`${ctx.basePath}${locale || ''}/somewhere-else`
)
expect(parsed.query).toEqual({}) expect(parsed.query).toEqual({})
} }
}
}) })
it('should apply headers correctly', async () => { it('should apply headers correctly', async () => {
for (const path of ['/add-header', '/en-US/add-header', '/nl/add-header']) { for (const [path, shouldAdd] of [
['/en-US/add-header-1', true],
['/en/add-header-1', false],
['/nl/add-header-2', true],
['/fr/add-header-2', false],
['/add-header-3', true],
['/en/add-header-3', true],
['/nl-NL/add-header-3', true],
]) {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
ctx.appPort, ctx.appPort,
`${ctx.basePath}${path}`, `${ctx.basePath}${path}`,
...@@ -337,30 +358,69 @@ export function runTests(ctx) { ...@@ -337,30 +358,69 @@ export function runTests(ctx) {
} }
) )
expect(res.status).toBe(404) expect(res.status).toBe(404)
expect(res.headers.get('x-hello')).toBe('world') expect(res.headers.get('x-hello')).toBe(shouldAdd ? 'world' : null)
} }
}) })
it('should apply rewrites correctly', async () => { it('should apply rewrites correctly', async () => {
const checks = [ let res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath}/en-US/rewrite-1`,
undefined,
{ {
locale: 'en-US', redirect: 'manual',
path: '/rewrite', }
}, )
expect(res.status).toBe(200)
let html = await res.text()
let $ = cheerio.load(html)
expect($('html').attr('lang')).toBe('en-US')
expect($('#router-locale').text()).toBe('en-US')
expect($('#router-pathname').text()).toBe('/another')
expect($('#router-as-path').text()).toBe('/rewrite-1')
res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath}/nl/rewrite-2`,
undefined,
{ {
locale: 'en-US', redirect: 'manual',
path: '/en-US/rewrite', }
}, )
expect(res.status).toBe(200)
html = await res.text()
$ = cheerio.load(html)
expect($('html').attr('lang')).toBe('nl')
expect($('#router-locale').text()).toBe('nl')
expect($('#router-pathname').text()).toBe('/another')
expect($('#router-as-path').text()).toBe('/rewrite-2')
res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath}/fr/rewrite-3`,
undefined,
{ {
locale: 'nl', redirect: 'manual',
path: '/nl/rewrite', }
}, )
]
for (const check of checks) { expect(res.status).toBe(200)
const res = await fetchViaHTTP(
html = await res.text()
$ = cheerio.load(html)
expect($('html').attr('lang')).toBe('nl')
expect($('#router-locale').text()).toBe('nl')
expect($('#router-pathname').text()).toBe('/another')
expect($('#router-as-path').text()).toBe('/rewrite-3')
for (const locale of locales) {
res = await fetchViaHTTP(
ctx.appPort, ctx.appPort,
`${ctx.basePath}${check.path}`, `${ctx.basePath}/${locale}/rewrite-4`,
undefined, undefined,
{ {
redirect: 'manual', redirect: 'manual',
...@@ -369,12 +429,27 @@ export function runTests(ctx) { ...@@ -369,12 +429,27 @@ export function runTests(ctx) {
expect(res.status).toBe(200) expect(res.status).toBe(200)
const html = await res.text() html = await res.text()
const $ = cheerio.load(html) $ = cheerio.load(html)
expect($('html').attr('lang')).toBe(check.locale) expect($('html').attr('lang')).toBe(locale)
expect($('#router-locale').text()).toBe(check.locale) expect($('#router-locale').text()).toBe(locale)
expect($('#router-pathname').text()).toBe('/another') expect($('#router-pathname').text()).toBe('/another')
expect($('#router-as-path').text()).toBe('/rewrite') expect($('#router-as-path').text()).toBe('/rewrite-4')
res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath}/${locale}/rewrite-5`,
undefined,
{
redirect: 'manual',
}
)
expect(res.status).toBe(200)
const json = await res.json()
expect(json.url).toBe('/')
expect(json.external).toBe(true)
} }
}) })
......
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