Unverified Commit 54b70425 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Ensure i18n with basePath works properly (#19083)

parent 41866a13
...@@ -85,7 +85,7 @@ export function createEntrypoints( ...@@ -85,7 +85,7 @@ export function createEntrypoints(
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
generateEtags: config.generateEtags, generateEtags: config.generateEtags,
poweredByHeader: config.poweredByHeader, poweredByHeader: config.poweredByHeader,
canonicalBase: config.canonicalBase, canonicalBase: config.amp.canonicalBase,
basePath: config.basePath, basePath: config.basePath,
runtimeConfig: hasRuntimeConfig runtimeConfig: hasRuntimeConfig
? JSON.stringify({ ? JSON.stringify({
......
...@@ -8,6 +8,7 @@ import { ...@@ -8,6 +8,7 @@ import {
BUILD_MANIFEST, BUILD_MANIFEST,
REACT_LOADABLE_MANIFEST, REACT_LOADABLE_MANIFEST,
ROUTES_MANIFEST, ROUTES_MANIFEST,
TEMPORARY_REDIRECT_STATUS,
} from '../../../next-server/lib/constants' } from '../../../next-server/lib/constants'
import { isDynamicRoute } from '../../../next-server/lib/router/utils' import { isDynamicRoute } from '../../../next-server/lib/router/utils'
import { __ApiPreviewProps } from '../../../next-server/server/api-utils' import { __ApiPreviewProps } from '../../../next-server/server/api-utils'
...@@ -361,11 +362,11 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -361,11 +362,11 @@ const nextServerlessLoader: loader.Loader = function () {
localeDomainRedirect localeDomainRedirect
? localeDomainRedirect ? localeDomainRedirect
: shouldStripDefaultLocale : shouldStripDefaultLocale
? '/' ? "${basePath}" || '/'
: \`/\${detectedLocale}\`, : \`${basePath}/\${detectedLocale}\`,
}) })
) )
res.statusCode = 307 res.statusCode = ${TEMPORARY_REDIRECT_STATUS}
res.end() res.end()
return return
} }
......
...@@ -475,7 +475,8 @@ export default class Router implements BaseRouter { ...@@ -475,7 +475,8 @@ export default class Router implements BaseRouter {
this.changeState( this.changeState(
'replaceState', 'replaceState',
formatWithValidation({ pathname: addBasePath(pathname), query }), formatWithValidation({ pathname: addBasePath(pathname), query }),
getURL() getURL(),
{ locale }
) )
} }
...@@ -621,7 +622,7 @@ export default class Router implements BaseRouter { ...@@ -621,7 +622,7 @@ export default class Router implements BaseRouter {
normalizeLocalePath, normalizeLocalePath,
} = require('../i18n/normalize-locale-path') as typeof import('../i18n/normalize-locale-path') } = require('../i18n/normalize-locale-path') as typeof import('../i18n/normalize-locale-path')
const parsedAs = parseRelativeUrl(as) const parsedAs = parseRelativeUrl(hasBasePath(as) ? delBasePath(as) : as)
const localePathResult = normalizeLocalePath( const localePathResult = normalizeLocalePath(
parsedAs.pathname, parsedAs.pathname,
...@@ -630,7 +631,7 @@ export default class Router implements BaseRouter { ...@@ -630,7 +631,7 @@ export default class Router implements BaseRouter {
if (localePathResult.detectedLocale) { if (localePathResult.detectedLocale) {
this.locale = localePathResult.detectedLocale this.locale = localePathResult.detectedLocale
url = localePathResult.pathname url = addBasePath(localePathResult.pathname)
} }
} }
...@@ -646,8 +647,13 @@ export default class Router implements BaseRouter { ...@@ -646,8 +647,13 @@ export default class Router implements BaseRouter {
this.abortComponentLoad(this._inFlightRoute) this.abortComponentLoad(this._inFlightRoute)
} }
as = addLocale(as, options.locale, this.defaultLocale) as = addBasePath(
addLocale(
hasBasePath(as) ? delBasePath(as) : as,
options.locale,
this.defaultLocale
)
)
const cleanedAs = delLocale( const cleanedAs = delLocale(
hasBasePath(as) ? delBasePath(as) : as, hasBasePath(as) ? delBasePath(as) : as,
this.locale this.locale
...@@ -848,12 +854,7 @@ export default class Router implements BaseRouter { ...@@ -848,12 +854,7 @@ export default class Router implements BaseRouter {
} }
Router.events.emit('beforeHistoryChange', as) Router.events.emit('beforeHistoryChange', as)
this.changeState( this.changeState(method, url, as, options)
method,
url,
addLocale(as, options.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
...@@ -1230,7 +1231,7 @@ export default class Router implements BaseRouter { ...@@ -1230,7 +1231,7 @@ export default class Router implements BaseRouter {
const pages = await this.pageLoader.getPageList() const pages = await this.pageLoader.getPageList()
parsed = this._resolveHref(parsed, pages) as typeof parsed parsed = this._resolveHref(parsed, pages, false) as typeof parsed
if (parsed.pathname !== pathname) { if (parsed.pathname !== pathname) {
pathname = parsed.pathname pathname = parsed.pathname
......
...@@ -315,9 +315,11 @@ export default class Server { ...@@ -315,9 +315,11 @@ export default class Server {
req.url = req.url!.replace(basePath, '') || '/' req.url = req.url!.replace(basePath, '') || '/'
} }
if (i18n && !parsedUrl.pathname?.startsWith('/_next')) { if (i18n && !req.url?.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 || '/') let { pathname, ...parsed } = parseUrl(req.url || '/')
pathname = pathname || '/'
let defaultLocale = i18n.defaultLocale let defaultLocale = i18n.defaultLocale
let detectedLocale = detectLocaleCookie(req, i18n.locales) let detectedLocale = detectLocaleCookie(req, i18n.locales)
let acceptPreferredLocale = let acceptPreferredLocale =
...@@ -348,13 +350,13 @@ export default class Server { ...@@ -348,13 +350,13 @@ export default class Server {
pathname: localePathResult.pathname, pathname: localePathResult.pathname,
}) })
;(req as any).__nextStrippedLocale = true ;(req as any).__nextStrippedLocale = true
parsedUrl.pathname = localePathResult.pathname parsedUrl.pathname = `${basePath || ''}${localePathResult.pathname}`
} }
// If a detected locale is a domain specific locale and we aren't already // If a detected locale is a domain specific locale and we aren't already
// on that domain and path prefix redirect to it to prevent duplicate // on that domain and path prefix redirect to it to prevent duplicate
// content from multiple domains // content from multiple domains
if (detectedDomain && parsedUrl.pathname === '/') { if (detectedDomain && pathname === '/') {
const localeToCheck = acceptPreferredLocale const localeToCheck = acceptPreferredLocale
// const localeToCheck = localePathResult.detectedLocale // const localeToCheck = localePathResult.detectedLocale
// ? detectedLocale // ? detectedLocale
...@@ -429,8 +431,8 @@ export default class Server { ...@@ -429,8 +431,8 @@ export default class Server {
pathname: localeDomainRedirect pathname: localeDomainRedirect
? localeDomainRedirect ? localeDomainRedirect
: shouldStripDefaultLocale : shouldStripDefaultLocale
? '/' ? basePath || `/`
: `/${detectedLocale}`, : `${basePath || ''}/${detectedLocale}`,
}) })
) )
res.statusCode = 307 res.statusCode = 307
...@@ -710,7 +712,7 @@ export default class Server { ...@@ -710,7 +712,7 @@ export default class Server {
type: redirectRoute.type, type: redirectRoute.type,
match: redirectRoute.match, match: redirectRoute.match,
statusCode: redirectRoute.statusCode, statusCode: redirectRoute.statusCode,
name: `Redirect route`, name: `Redirect route ${redirectRoute.source}`,
fn: async (req, res, params, parsedUrl) => { fn: async (req, res, params, parsedUrl) => {
const { parsedDestination } = prepareDestination( const { parsedDestination } = prepareDestination(
redirectRoute.destination, redirectRoute.destination,
...@@ -750,7 +752,7 @@ export default class Server { ...@@ -750,7 +752,7 @@ export default class Server {
...rewriteRoute, ...rewriteRoute,
check: true, check: true,
type: rewriteRoute.type, type: rewriteRoute.type,
name: `Rewrite route`, name: `Rewrite route ${rewriteRoute.source}`,
match: rewriteRoute.match, match: rewriteRoute.match,
fn: async (req, res, params, parsedUrl) => { fn: async (req, res, params, parsedUrl) => {
const { newUrl, parsedDestination } = prepareDestination( const { newUrl, parsedDestination } = prepareDestination(
......
...@@ -183,9 +183,17 @@ export default class Router { ...@@ -183,9 +183,17 @@ export default class Router {
(req as any).__nextStrippedLocale && (req as any).__nextStrippedLocale &&
parsedUrl.query.__nextLocale parsedUrl.query.__nextLocale
) { ) {
if (keepBasePath) {
currentPathname = replaceBasePath(this.basePath, currentPathname!)
}
currentPathname = `/${parsedUrl.query.__nextLocale}${ currentPathname = `/${parsedUrl.query.__nextLocale}${
currentPathname === '/' ? '' : currentPathname currentPathname === '/' ? '' : currentPathname
}` }`
if (keepBasePath) {
currentPathname = `${this.basePath}${currentPathname}`
}
} }
const newParams = testRoute.match(currentPathname) const newParams = testRoute.match(currentPathname)
......
...@@ -101,7 +101,7 @@ describe('Build Output', () => { ...@@ -101,7 +101,7 @@ describe('Build Output', () => {
expect(parseFloat(err404Size) - 3.6).toBeLessThanOrEqual(0) expect(parseFloat(err404Size) - 3.6).toBeLessThanOrEqual(0)
expect(err404Size.endsWith('kB')).toBe(true) expect(err404Size.endsWith('kB')).toBe(true)
expect(parseFloat(err404FirstLoad) - 64.9).toBeLessThanOrEqual(0) expect(parseFloat(err404FirstLoad) - 65).toBeLessThanOrEqual(0)
expect(err404FirstLoad.endsWith('kB')).toBe(true) expect(err404FirstLoad.endsWith('kB')).toBe(true)
expect(parseFloat(sharedByAll) - 61.5).toBeLessThanOrEqual(0) expect(parseFloat(sharedByAll) - 61.5).toBeLessThanOrEqual(0)
......
module.exports = {
// target: 'experimental-serverless-trace',
// basePath: '/docs',
i18n: {
// localeDetection: false,
locales: ['nl-NL', 'nl-BE', 'nl', 'fr-BE', 'fr', 'en-US', 'en'],
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'],
},
{
http: true,
domain: 'example.fr',
defaultLocale: 'fr',
locales: ['fr-BE'],
},
],
},
async redirects() {
return [
{
source: '/en-US/redirect',
destination: '/somewhere-else',
permanent: false,
},
{
source: '/nl/redirect',
destination: '/somewhere-else',
permanent: false,
},
{
source: '/redirect',
destination: '/somewhere-else',
permanent: false,
},
]
},
async rewrites() {
return [
{
source: '/en-US/rewrite',
destination: '/another',
},
{
source: '/nl/rewrite',
destination: '/another',
},
{
source: '/rewrite',
destination: '/another',
},
]
},
async headers() {
return [
{
source: '/en-US/add-header',
headers: [
{
key: 'x-hello',
value: 'world',
},
],
},
{
source: '/nl/add-header',
headers: [
{
key: 'x-hello',
value: 'world',
},
],
},
{
source: '/add-header',
headers: [
{
key: 'x-hello',
value: 'world',
},
],
},
]
},
}
export default function NotFound(props) {
return (
<>
<h1 id="not-found">This page could not be found | 404</h1>
<p id="props">{JSON.stringify(props)}</p>
</>
)
}
export const getStaticProps = ({ locale, locales, defaultLocale }) => {
return {
props: {
locale,
locales,
defaultLocale,
is404: true,
},
}
}
if (typeof window !== 'undefined') {
window.caughtWarns = []
const origWarn = window.console.warn
const origError = window.console.error
window.console.warn = function (...args) {
window.caughtWarns.push(args.join(' '))
origWarn(...args)
}
window.console.error = function (...args) {
window.caughtWarns.push(args.join(' '))
origError(...args)
}
}
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
import { useAmp } from 'next/amp'
import { useRouter } from 'next/router'
export const config = {
amp: true,
}
export default function Page(props) {
const router = useRouter()
return (
<>
<p id="another">another page</p>
<p id="is-amp">{useAmp() ? 'yes' : 'no'}</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="router-locale">{router.locale}</p>
<p id="router-locales">{JSON.stringify(router.locales)}</p>
<p id="router-query">{JSON.stringify(router.query)}</p>
<p id="router-pathname">{router.pathname}</p>
<p id="router-as-path">{router.asPath}</p>
</>
)
}
export const getServerSideProps = ({ locale, locales }) => {
return {
props: {
locale,
locales,
},
}
}
import { useAmp } from 'next/amp'
import { useRouter } from 'next/router'
export const config = {
amp: 'hybrid',
}
export default function Page(props) {
const router = useRouter()
return (
<>
<p id="another">another page</p>
<p id="is-amp">{useAmp() ? 'yes' : 'no'}</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="router-locale">{router.locale}</p>
<p id="router-locales">{JSON.stringify(router.locales)}</p>
<p id="router-query">{JSON.stringify(router.query)}</p>
<p id="router-pathname">{router.pathname}</p>
<p id="router-as-path">{router.asPath}</p>
</>
)
}
import Link from 'next/link'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
return (
<>
<p id="another">another page</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="router-locale">{router.locale}</p>
<p id="router-default-locale">{router.defaultLocale}</p>
<p id="router-locales">{JSON.stringify(router.locales)}</p>
<p id="router-query">{JSON.stringify(router.query)}</p>
<p id="router-pathname">{router.pathname}</p>
<p id="router-as-path">{router.asPath}</p>
<Link href="/">
<a id="to-index">to /</a>
</Link>
<br />
</>
)
}
export const getServerSideProps = ({ locale, locales, defaultLocale }) => {
return {
props: {
locale,
locales,
defaultLocale,
},
}
}
import Link from 'next/link'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
return (
<>
<p id="auto-export">auto-export page</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="router-locale">{router.locale}</p>
<p id="router-locales">{JSON.stringify(router.locales)}</p>
<p id="router-query">{JSON.stringify(router.query)}</p>
<p id="router-pathname">{router.pathname}</p>
<p id="router-as-path">{router.asPath}</p>
<Link href="/">
<a id="to-index">to /</a>
</Link>
</>
)
}
import Link from 'next/link'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
return (
<>
<p id="dynamic">dynamic page</p>
<p id="router-locale">{router.locale}</p>
<p id="router-default-locale">{router.defaultLocale}</p>
<p id="router-locales">{JSON.stringify(router.locales)}</p>
<p id="router-query">{JSON.stringify(router.query)}</p>
<p id="router-pathname">{router.pathname}</p>
<p id="router-as-path">{router.asPath}</p>
<Link href="/another">
<a id="to-another">to /another</a>
</Link>
<br />
<Link href="/gsp">
<a id="to-gsp">to /gsp</a>
</Link>
<br />
<Link href="/gsp/fallback/first">
<a id="to-fallback-first">to /gsp/fallback/first</a>
</Link>
<br />
<Link href="/gsp/fallback/hello">
<a id="to-fallback-hello">to /gsp/fallback/hello</a>
</Link>
<br />
<Link href="/gsp/no-fallback/first">
<a id="to-no-fallback-first">to /gsp/no-fallback/first</a>
</Link>
<br />
<Link href="/gssp">
<a id="to-gssp">to /gssp</a>
</Link>
<br />
<Link href="/gssp/first">
<a id="to-gssp-slug">to /gssp/first</a>
</Link>
<br />
</>
)
}
import Link from 'next/link'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
return (
<>
<p id="frank">frank page</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="router-locale">{router.locale}</p>
<p id="router-default-locale">{router.defaultLocale}</p>
<p id="router-locales">{JSON.stringify(router.locales)}</p>
<p id="router-query">{JSON.stringify(router.query)}</p>
<p id="router-pathname">{router.pathname}</p>
<p id="router-as-path">{router.asPath}</p>
<Link href="/another">
<a id="to-another">to /another</a>
</Link>
<br />
<Link href="/gsp">
<a id="to-gsp">to /gsp</a>
</Link>
<br />
<Link href="/gsp/fallback/first">
<a id="to-fallback-first">to /gsp/fallback/first</a>
</Link>
<br />
<Link href="/gsp/fallback/hello">
<a id="to-fallback-hello">to /gsp/fallback/hello</a>
</Link>
<br />
<Link href="/gsp/no-fallback/first">
<a id="to-no-fallback-first">to /gsp/no-fallback/first</a>
</Link>
<br />
<Link href="/gssp">
<a id="to-gssp">to /gssp</a>
</Link>
<br />
<Link href="/gssp/first">
<a id="to-gssp-slug">to /gssp/first</a>
</Link>
<br />
</>
)
}
export const getStaticProps = ({ locale, locales, defaultLocale }) => {
return {
props: {
locale,
locales,
defaultLocale,
},
}
}
import Link from 'next/link'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
if (router.isFallback) return 'Loading...'
return (
<>
<p id="gsp">gsp page</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="router-locale">{router.locale}</p>
<p id="router-default-locale">{router.defaultLocale}</p>
<p id="router-locales">{JSON.stringify(router.locales)}</p>
<p id="router-query">{JSON.stringify(router.query)}</p>
<p id="router-pathname">{router.pathname}</p>
<p id="router-as-path">{router.asPath}</p>
<Link href="/">
<a id="to-index">to /</a>
</Link>
<br />
</>
)
}
export const getStaticProps = ({ params, locale, locales, defaultLocale }) => {
// ensure getStaticProps isn't called without params
if (!params || !params.slug) {
throw new Error(`missing params ${JSON.stringify(params)}`)
}
if (params && params.slug === 'mixed-not-found-redirect') {
return {
notFound: true,
redirect: {
destination: '/another',
permanent: false,
},
}
}
return {
props: {
params,
locale,
locales,
defaultLocale,
},
}
}
export const getStaticPaths = ({ locales, defaultLocale }) => {
// make sure locales were provided correctly
if (!locales || locales.length !== 7) {
throw new Error(
'locales missing in getStaticPaths!! got: ' + JSON.stringify(locales)
)
}
if (!defaultLocale) {
throw new Error('missing defaultLocale in getStaticPaths')
}
return {
// the default locale will be used since one isn't defined here
paths: ['first', 'second'].map((slug) => ({
params: { slug },
})),
fallback: true,
}
}
import Link from 'next/link'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
return (
<>
<p id="gsp">gsp page</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="router-locale">{router.locale}</p>
<p id="router-locales">{JSON.stringify(router.locales)}</p>
<p id="router-query">{JSON.stringify(router.query)}</p>
<p id="router-pathname">{router.pathname}</p>
<p id="router-as-path">{router.asPath}</p>
<Link href="/">
<a id="to-index">to /</a>
</Link>
<br />
</>
)
}
export const getStaticProps = ({ locale, locales, defaultLocale }) => {
return {
props: {
locale,
locales,
defaultLocale,
},
}
}
import Link from 'next/link'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
if (router.isFallback) return 'Loading...'
return (
<>
<p id="gsp">gsp page</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="router-locale">{router.locale}</p>
<p id="router-default-locale">{router.defaultLocale}</p>
<p id="router-locales">{JSON.stringify(router.locales)}</p>
<p id="router-query">{JSON.stringify(router.query)}</p>
<p id="router-pathname">{router.pathname}</p>
<p id="router-as-path">{router.asPath}</p>
<Link href="/">
<a id="to-index">to /</a>
</Link>
<br />
</>
)
}
export const getStaticProps = ({ params, locale, locales, defaultLocale }) => {
// ensure getStaticProps isn't called without params
if (!params || !params.slug) {
throw new Error(`missing params ${JSON.stringify(params)}`)
}
return {
props: {
params,
locale,
locales,
defaultLocale,
},
}
}
export const getStaticPaths = () => {
return {
paths: [
{ params: { slug: 'first' } },
'/gsp/no-fallback/second',
{ params: { slug: 'first' }, locale: 'en-US' },
'/nl-NL/gsp/no-fallback/second',
],
fallback: false,
}
}
import Link from 'next/link'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
return (
<>
<p id="gssp">gssp page</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="router-locale">{router.locale}</p>
<p id="router-locales">{JSON.stringify(router.locales)}</p>
<p id="router-query">{JSON.stringify(router.query)}</p>
<p id="router-pathname">{router.pathname}</p>
<p id="router-as-path">{router.asPath}</p>
<Link href="/">
<a id="to-index">to /</a>
</Link>
<br />
</>
)
}
export const getServerSideProps = ({
params,
locale,
locales,
defaultLocale,
}) => {
return {
props: {
params,
locale,
locales,
defaultLocale,
},
}
}
import Link from 'next/link'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
return (
<>
<p id="gssp">gssp page</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="router-locale">{router.locale}</p>
<p id="router-default-locale">{router.defaultLocale}</p>
<p id="router-locales">{JSON.stringify(router.locales)}</p>
<p id="router-query">{JSON.stringify(router.query)}</p>
<p id="router-pathname">{router.pathname}</p>
<p id="router-as-path">{router.asPath}</p>
<Link href="/">
<a id="to-index">to /</a>
</Link>
<br />
</>
)
}
export const getServerSideProps = ({ locale, locales, defaultLocale }) => {
return {
props: {
locale,
locales,
defaultLocale,
},
}
}
import Link from 'next/link'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
return (
<>
<p id="index">index page</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="router-locale">{router.locale}</p>
<p id="router-default-locale">{router.defaultLocale}</p>
<p id="router-locales">{JSON.stringify(router.locales)}</p>
<p id="router-query">{JSON.stringify(router.query)}</p>
<p id="router-pathname">{router.pathname}</p>
<p id="router-as-path">{router.asPath}</p>
<Link href="/another">
<a id="to-another">to /another</a>
</Link>
<br />
<Link href="/dynamic/first">
<a id="to-dynamic">to /dynamic/first</a>
</Link>
<br />
<Link href="/gsp">
<a id="to-gsp">to /gsp</a>
</Link>
<br />
<Link href="/gsp/fallback/first">
<a id="to-fallback-first">to /gsp/fallback/first</a>
</Link>
<br />
<Link href="/gsp/fallback/hello">
<a id="to-fallback-hello">to /gsp/fallback/hello</a>
</Link>
<br />
<Link href="/gsp/no-fallback/first">
<a id="to-no-fallback-first">to /gsp/no-fallback/first</a>
</Link>
<br />
<Link href="/gssp">
<a id="to-gssp">to /gssp</a>
</Link>
<br />
<Link href="/gssp/first">
<a id="to-gssp-slug">to /gssp/first</a>
</Link>
<br />
</>
)
}
export const getStaticProps = ({ locale, locales, defaultLocale }) => {
return {
props: {
locale,
locales,
defaultLocale,
},
}
}
import Link from 'next/link'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
const { nextLocale } = router.query
return (
<>
<p id="links">links page</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="router-locale">{router.locale}</p>
<p id="router-default-locale">{router.defaultLocale}</p>
<p id="router-locales">{JSON.stringify(router.locales)}</p>
<p id="router-query">{JSON.stringify(router.query)}</p>
<p id="router-pathname">{router.pathname}</p>
<p id="router-as-path">{router.asPath}</p>
<Link href="/another" locale={nextLocale}>
<a id="to-another">to /another</a>
</Link>
<br />
<Link href="/gsp" locale={nextLocale}>
<a id="to-gsp">to /gsp</a>
</Link>
<br />
<Link href="/gsp/fallback/first" locale={nextLocale}>
<a id="to-fallback-first">to /gsp/fallback/first</a>
</Link>
<br />
<Link href="/gsp/fallback/hello" locale={nextLocale}>
<a id="to-fallback-hello">to /gsp/fallback/hello</a>
</Link>
<br />
<Link href="/gsp/no-fallback/first" locale={nextLocale}>
<a id="to-no-fallback-first">to /gsp/no-fallback/first</a>
</Link>
<br />
<Link href="/gssp" locale={nextLocale}>
<a id="to-gssp">to /gssp</a>
</Link>
<br />
<Link href="/gssp/first" locale={nextLocale}>
<a id="to-gssp-slug">to /gssp/first</a>
</Link>
<br />
</>
)
}
// make SSR page so we have query values immediately
export const getServerSideProps = () => {
return {
props: {},
}
}
import Link from 'next/link'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
const { nextLocale } = router.query
return (
<>
<p id="links">links page</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="router-locale">{router.locale}</p>
<p id="router-locales">{JSON.stringify(router.locales)}</p>
<p id="router-query">{JSON.stringify(router.query)}</p>
<p id="router-pathname">{router.pathname}</p>
<p id="router-as-path">{router.asPath}</p>
<Link href={`/${nextLocale}/another`} locale={false}>
<a id="to-another">to /another</a>
</Link>
<br />
<Link href={`/${nextLocale}/gsp`} locale={false}>
<a id="to-gsp">to /gsp</a>
</Link>
<br />
<Link href={`/${nextLocale}/gsp/fallback/first`} locale={false}>
<a id="to-fallback-first">to /gsp/fallback/first</a>
</Link>
<br />
<Link href={`/${nextLocale}/gsp/fallback/hello`} locale={false}>
<a id="to-fallback-hello">to /gsp/fallback/hello</a>
</Link>
<br />
<Link href={`/${nextLocale}/gsp/no-fallback/first`} locale={false}>
<a id="to-no-fallback-first">to /gsp/no-fallback/first</a>
</Link>
<br />
<Link href={`/${nextLocale}/gssp`} locale={false}>
<a id="to-gssp">to /gssp</a>
</Link>
<br />
<Link href={`/${nextLocale}/gssp/first`} locale={false}>
<a id="to-gssp-slug">to /gssp/first</a>
</Link>
<br />
</>
)
}
// make SSR page so we have query values immediately
export const getServerSideProps = () => {
return {
props: {},
}
}
import Link from 'next/link'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
return (
<>
<p id="gsp">gsp page</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="router-locale">{router.locale}</p>
<p id="router-locales">{JSON.stringify(router.locales)}</p>
<p id="router-query">{JSON.stringify(router.query)}</p>
<p id="router-pathname">{router.pathname}</p>
<p id="router-as-path">{router.asPath}</p>
<Link href="/">
<a id="to-index">to /</a>
</Link>
<br />
</>
)
}
export const getStaticProps = ({ params, locale, locales }) => {
// ensure getStaticProps isn't called without params
if (!params || !params.slug) {
throw new Error(`missing params ${JSON.stringify(params)}`)
}
if (locale === 'en' || locale === 'nl') {
return {
notFound: true,
}
}
return {
props: {
params,
locale,
locales,
},
}
}
export const getStaticPaths = () => {
return {
// the default locale will be used since one isn't defined here
paths: ['first', 'second'].map((slug) => ({
params: { slug },
})),
fallback: 'blocking',
}
}
import Link from 'next/link'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
if (router.isFallback) return 'Loading...'
return (
<>
<p id="gsp">gsp page</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="router-locale">{router.locale}</p>
<p id="router-locales">{JSON.stringify(router.locales)}</p>
<p id="router-query">{JSON.stringify(router.query)}</p>
<p id="router-pathname">{router.pathname}</p>
<p id="router-as-path">{router.asPath}</p>
<Link href="/">
<a id="to-index">to /</a>
</Link>
<br />
</>
)
}
export const getStaticProps = ({ params, locale, locales }) => {
// ensure getStaticProps isn't called without params
if (!params || !params.slug) {
throw new Error(`missing params ${JSON.stringify(params)}`)
}
if (locale === 'en' || locale === 'nl') {
return {
notFound: true,
}
}
return {
props: {
params,
locale,
locales,
},
}
}
export const getStaticPaths = () => {
return {
// the default locale will be used since one isn't defined here
paths: ['first', 'second'].map((slug) => ({
params: { slug },
})),
fallback: true,
}
}
import Link from 'next/link'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
return (
<>
<p id="gsp">gsp page</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="router-locale">{router.locale}</p>
<p id="router-locales">{JSON.stringify(router.locales)}</p>
<p id="router-query">{JSON.stringify(router.query)}</p>
<p id="router-pathname">{router.pathname}</p>
<p id="router-as-path">{router.asPath}</p>
<Link href="/">
<a id="to-index">to /</a>
</Link>
<br />
</>
)
}
export const getStaticProps = ({ locale, locales }) => {
if (locale === 'en' || locale === 'nl') {
return {
notFound: true,
}
}
return {
props: {
locale,
locales,
},
}
}
import http from 'http'
import fs from 'fs-extra'
import { join } from 'path'
import cheerio from 'cheerio'
import { runTests, locales } from '../../i18n-support/test/shared'
import {
nextBuild,
nextStart,
findPort,
killApp,
getPageFileFromPagesManifest,
fetchViaHTTP,
File,
launchApp,
} from 'next-test-utils'
const appDir = join(__dirname, '../')
const nextConfig = new File(join(appDir, 'next.config.js'))
const ctx = {
basePath: '/docs',
appDir,
}
describe('i18n Support', () => {
describe('dev mode', () => {
const curCtx = {
...ctx,
isDev: true,
}
beforeAll(async () => {
nextConfig.replace('// basePath', 'basePath')
await fs.remove(join(appDir, '.next'))
curCtx.appPort = await findPort()
curCtx.app = await launchApp(appDir, curCtx.appPort)
})
afterAll(async () => {
nextConfig.restore()
await killApp(curCtx.app)
})
runTests(curCtx)
})
describe('production mode', () => {
beforeAll(async () => {
nextConfig.replace('// basePath', 'basePath')
await fs.remove(join(appDir, '.next'))
await nextBuild(appDir)
ctx.appPort = await findPort()
ctx.app = await nextStart(appDir, ctx.appPort)
ctx.buildPagesDir = join(appDir, '.next/server/pages')
ctx.buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
})
afterAll(async () => {
nextConfig.restore()
await killApp(ctx.app)
})
runTests(ctx)
})
describe('serverless mode', () => {
beforeAll(async () => {
await fs.remove(join(appDir, '.next'))
nextConfig.replace('// target', 'target')
nextConfig.replace('// basePath', 'basePath')
await nextBuild(appDir)
ctx.appPort = await findPort()
ctx.app = await nextStart(appDir, ctx.appPort)
ctx.buildPagesDir = join(appDir, '.next/serverless/pages')
ctx.buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
})
afterAll(async () => {
nextConfig.restore()
await killApp(ctx.app)
})
it('should have correct props for blocking notFound', async () => {
const serverFile = getPageFileFromPagesManifest(
appDir,
'/not-found/blocking-fallback/[slug]'
)
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 res = await fetchViaHTTP(
appPort,
`${ctx.basePath}/nl/not-found/blocking-fallback/first`
)
server.close()
expect(res.status).toBe(404)
const $ = cheerio.load(await res.text())
const props = JSON.parse($('#props').text())
expect($('#not-found').text().length > 0).toBe(true)
expect(props).toEqual({
is404: true,
locale: 'nl',
locales,
defaultLocale: 'en-US',
})
})
runTests(ctx)
})
describe('with localeDetection disabled', () => {
beforeAll(async () => {
await fs.remove(join(appDir, '.next'))
nextConfig.replace('// basePath', 'basePath')
nextConfig.replace('// localeDetection', 'localeDetection')
await nextBuild(appDir)
ctx.appPort = await findPort()
ctx.app = await nextStart(appDir, ctx.appPort)
})
afterAll(async () => {
nextConfig.restore()
await killApp(ctx.app)
})
it('should have localeDetection in routes-manifest', async () => {
const routesManifest = await fs.readJSON(
join(appDir, '.next/routes-manifest.json')
)
expect(routesManifest.i18n).toEqual({
localeDetection: false,
locales: ['en-US', 'nl-NL', 'nl-BE', 'nl', 'fr-BE', 'fr', 'en'],
defaultLocale: 'en-US',
domains: [
{
http: true,
domain: 'example.be',
defaultLocale: 'nl-BE',
locales: ['nl', 'nl-NL', 'nl-BE'],
},
{
http: true,
domain: 'example.fr',
defaultLocale: 'fr',
locales: ['fr-BE'],
},
],
})
})
it('should not detect locale from accept-language', async () => {
const res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath || '/'}`,
{},
{
redirect: 'manual',
headers: {
'accept-language': 'fr',
},
}
)
expect(res.status).toBe(200)
const $ = cheerio.load(await res.text())
expect($('html').attr('lang')).toBe('en-US')
expect($('#router-locale').text()).toBe('en-US')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect($('#router-pathname').text()).toBe('/')
expect($('#router-as-path').text()).toBe('/')
})
it('should set locale from detected path', async () => {
for (const locale of locales) {
const res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath}/${locale}`,
{},
{
redirect: 'manual',
headers: {
'accept-language': 'en-US,en;q=0.9',
},
}
)
expect(res.status).toBe(200)
const $ = cheerio.load(await res.text())
expect($('html').attr('lang')).toBe(locale)
expect($('#router-locale').text()).toBe(locale)
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect($('#router-pathname').text()).toBe('/')
expect($('#router-as-path').text()).toBe('/')
}
})
})
})
module.exports = { module.exports = {
// target: 'experimental-serverless-trace', // target: 'experimental-serverless-trace',
// basePath: '/docs',
i18n: { i18n: {
// localeDetection: false, // 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'],
......
/* eslint-env jest */
import http from 'http' import http from 'http'
import url from 'url'
import fs from 'fs-extra' import fs from 'fs-extra'
import cheerio from 'cheerio'
import { join } from 'path' import { join } from 'path'
import webdriver from 'next-webdriver' import cheerio from 'cheerio'
import escapeRegex from 'escape-string-regexp' import { runTests, locales } from './shared'
import assert from 'assert'
import { import {
fetchViaHTTP,
findPort,
killApp,
launchApp,
nextBuild, nextBuild,
nextStart, nextStart,
renderViaHTTP, findPort,
File, killApp,
waitFor,
normalizeRegEx,
getPageFileFromPagesManifest, getPageFileFromPagesManifest,
check, fetchViaHTTP,
File,
launchApp,
} from 'next-test-utils' } from 'next-test-utils'
jest.setTimeout(1000 * 60 * 2)
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
const nextConfig = new File(join(appDir, 'next.config.js')) const nextConfig = new File(join(appDir, 'next.config.js'))
let app const ctx = {
let appPort basePath: '',
let buildPagesDir appDir,
let buildId
const locales = ['en-US', 'nl-NL', 'nl-BE', 'nl', 'fr-BE', 'fr', 'en']
async function addDefaultLocaleCookie(browser) {
// make sure default locale is used in case browser isn't set to
// favor en-US by default, (we use all caps to ensure it's case-insensitive)
await browser.manage().addCookie({ name: 'NEXT_LOCALE', value: 'EN-US' })
await browser.get(browser.initUrl)
}
function runTests(isDev) {
if (isDev) {
it('should show error for redirect and notFound returned at same time', async () => {
const html = await renderViaHTTP(
appPort,
'/_next/data/development/gsp/fallback/mixed-not-found-redirect.json'
)
expect(html).toContain(
'`redirect` and `notFound` can not both be returned from getStaticProps at the same time. Page: /gsp/fallback/[slug]'
)
})
}
it('should have correct values for non-prefixed path', async () => {
for (const paths of [
['/links', '/links'],
['/another', '/another'],
['/gsp/fallback/first', '/gsp/fallback/[slug]'],
['/gsp/no-fallback/first', '/gsp/no-fallback/[slug]'],
]) {
const [asPath, pathname] = paths
const res = await fetchViaHTTP(appPort, asPath, undefined, {
redirect: 'manual',
headers: {
'accept-language': 'fr',
},
})
expect(res.status).toBe(200)
const $ = cheerio.load(await res.text())
expect($('html').attr('lang')).toBe('en-US')
expect($('#router-locale').text()).toBe('en-US')
expect($('#router-default-locale').text()).toBe('en-US')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect($('#router-pathname').text()).toBe(pathname)
expect($('#router-as-path').text()).toBe(asPath)
}
})
it('should not have hydration mis-match from hash', async () => {
const browser = await webdriver(appPort, '/en#')
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('en')
expect(await browser.elementByCss('#router-locale').text()).toBe('en')
expect(await browser.elementByCss('#router-default-locale').text()).toBe(
'en-US'
)
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(await browser.elementByCss('#router-pathname').text()).toBe('/')
expect(await browser.elementByCss('#router-as-path').text()).toBe('/')
expect(await browser.eval('window.caughtWarns')).toEqual([])
})
if (!isDev) {
it('should add i18n config to routes-manifest', async () => {
const routesManifest = await fs.readJSON(
join(appDir, '.next/routes-manifest.json')
)
expect(routesManifest.i18n).toEqual({
locales: ['en-US', 'nl-NL', 'nl-BE', 'nl', 'fr-BE', 'fr', 'en'],
defaultLocale: 'en-US',
domains: [
{
http: true,
domain: 'example.be',
defaultLocale: 'nl-BE',
locales: ['nl', 'nl-NL', 'nl-BE'],
},
{
http: true,
domain: 'example.fr',
defaultLocale: 'fr',
locales: ['fr-BE'],
},
],
})
})
it('should output correct prerender-manifest', async () => {
const prerenderManifest = await fs.readJSON(
join(appDir, '.next/prerender-manifest.json')
)
for (const key of Object.keys(prerenderManifest.dynamicRoutes)) {
const item = prerenderManifest.dynamicRoutes[key]
item.routeRegex = normalizeRegEx(item.routeRegex)
item.dataRouteRegex = normalizeRegEx(item.dataRouteRegex)
}
expect(prerenderManifest.routes).toEqual({
'/': {
dataRoute: `/_next/data/${buildId}/index.json`,
initialRevalidateSeconds: false,
srcRoute: null,
},
'/404': {
dataRoute: `/_next/data/${buildId}/404.json`,
initialRevalidateSeconds: false,
srcRoute: null,
},
'/en-US/gsp/fallback/first': {
dataRoute: `/_next/data/${buildId}/en-US/gsp/fallback/first.json`,
initialRevalidateSeconds: false,
srcRoute: '/gsp/fallback/[slug]',
},
'/en-US/gsp/fallback/second': {
dataRoute: `/_next/data/${buildId}/en-US/gsp/fallback/second.json`,
initialRevalidateSeconds: false,
srcRoute: '/gsp/fallback/[slug]',
},
'/en-US/gsp/no-fallback/first': {
dataRoute: `/_next/data/${buildId}/en-US/gsp/no-fallback/first.json`,
initialRevalidateSeconds: false,
srcRoute: '/gsp/no-fallback/[slug]',
},
'/en-US/gsp/no-fallback/second': {
dataRoute: `/_next/data/${buildId}/en-US/gsp/no-fallback/second.json`,
initialRevalidateSeconds: false,
srcRoute: '/gsp/no-fallback/[slug]',
},
'/en-US/not-found/blocking-fallback/first': {
dataRoute: `/_next/data/${buildId}/en-US/not-found/blocking-fallback/first.json`,
initialRevalidateSeconds: false,
srcRoute: '/not-found/blocking-fallback/[slug]',
},
'/en-US/not-found/blocking-fallback/second': {
dataRoute: `/_next/data/${buildId}/en-US/not-found/blocking-fallback/second.json`,
initialRevalidateSeconds: false,
srcRoute: '/not-found/blocking-fallback/[slug]',
},
'/en-US/not-found/fallback/first': {
dataRoute: `/_next/data/${buildId}/en-US/not-found/fallback/first.json`,
initialRevalidateSeconds: false,
srcRoute: '/not-found/fallback/[slug]',
},
'/en-US/not-found/fallback/second': {
dataRoute: `/_next/data/${buildId}/en-US/not-found/fallback/second.json`,
initialRevalidateSeconds: false,
srcRoute: '/not-found/fallback/[slug]',
},
'/frank': {
dataRoute: `/_next/data/${buildId}/frank.json`,
initialRevalidateSeconds: false,
srcRoute: null,
},
'/gsp': {
dataRoute: `/_next/data/${buildId}/gsp.json`,
srcRoute: null,
initialRevalidateSeconds: false,
},
'/nl-NL/gsp/no-fallback/second': {
dataRoute: `/_next/data/${buildId}/nl-NL/gsp/no-fallback/second.json`,
initialRevalidateSeconds: false,
srcRoute: '/gsp/no-fallback/[slug]',
},
'/not-found': {
dataRoute: `/_next/data/${buildId}/not-found.json`,
srcRoute: null,
initialRevalidateSeconds: false,
},
})
expect(prerenderManifest.dynamicRoutes).toEqual({
'/gsp/fallback/[slug]': {
routeRegex: normalizeRegEx(
'^\\/gsp\\/fallback\\/([^\\/]+?)(?:\\/)?$'
),
dataRoute: `/_next/data/${buildId}/gsp/fallback/[slug].json`,
fallback: '/gsp/fallback/[slug].html',
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/gsp\\/fallback\\/([^\\/]+?)\\.json$`
),
},
'/gsp/no-fallback/[slug]': {
routeRegex: normalizeRegEx(
'^\\/gsp\\/no\\-fallback\\/([^\\/]+?)(?:\\/)?$'
),
dataRoute: `/_next/data/${buildId}/gsp/no-fallback/[slug].json`,
fallback: false,
dataRouteRegex: normalizeRegEx(
`^/_next/data/${escapeRegex(
buildId
)}/gsp/no\\-fallback/([^/]+?)\\.json$`
),
},
'/not-found/blocking-fallback/[slug]': {
dataRoute: `/_next/data/${buildId}/not-found/blocking-fallback/[slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/not\\-found\\/blocking\\-fallback\\/([^\\/]+?)\\.json$`
),
fallback: null,
routeRegex: normalizeRegEx(
`^\\/not\\-found\\/blocking\\-fallback\\/([^\\/]+?)(?:\\/)?$`
),
},
'/not-found/fallback/[slug]': {
dataRoute: `/_next/data/${buildId}/not-found/fallback/[slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/not\\-found\\/fallback\\/([^\\/]+?)\\.json$`
),
fallback: '/not-found/fallback/[slug].html',
routeRegex: normalizeRegEx('^/not\\-found/fallback/([^/]+?)(?:/)?$'),
},
})
})
}
it('should resolve auto-export dynamic route correctly', async () => {
for (const locale of locales) {
const res = await fetchViaHTTP(
appPort,
`/${locale}/dynamic/first`,
undefined,
{
redirect: 'manual',
}
)
expect(res.status).toBe(200)
expect(await res.text()).toContain('dynamic page')
}
})
it('should navigate to auto-export dynamic page', async () => {
for (const locale of locales) {
const browser = await webdriver(appPort, `/${locale}`)
await browser.eval('window.beforeNav = 1')
await browser
.elementByCss('#to-dynamic')
.click()
.waitForElementByCss('#dynamic')
expect(await browser.eval('window.beforeNav')).toBe(1)
expect(await browser.elementByCss('#router-locale').text()).toBe(locale)
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ slug: 'first' })
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/dynamic/[slug]'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/dynamic/first'
)
expect(await browser.eval('window.location.pathname')).toBe(
`${locale === 'en-US' ? '' : `/${locale}`}/dynamic/first`
)
await browser.back().waitForElementByCss('#index')
expect(await browser.eval('window.beforeNav')).toBe(1)
expect(await browser.elementByCss('#router-locale').text()).toBe(locale)
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({})
expect(await browser.elementByCss('#router-pathname').text()).toBe('/')
expect(await browser.elementByCss('#router-as-path').text()).toBe('/')
}
})
it('should apply redirects correctly', async () => {
for (const path of ['/redirect', '/en-US/redirect', '/nl/redirect']) {
const res = await fetchViaHTTP(appPort, path, undefined, {
redirect: 'manual',
})
expect(res.status).toBe(307)
const parsed = url.parse(res.headers.get('location'), true)
expect(parsed.pathname).toBe('/somewhere-else')
expect(parsed.query).toEqual({})
}
})
it('should apply headers correctly', async () => {
for (const path of ['/add-header', '/en-US/add-header', '/nl/add-header']) {
const res = await fetchViaHTTP(appPort, path, undefined, {
redirect: 'manual',
})
expect(res.status).toBe(404)
expect(res.headers.get('x-hello')).toBe('world')
}
})
it('should apply rewrites correctly', async () => {
const checks = [
{
locale: 'en-US',
path: '/rewrite',
},
{
locale: 'en-US',
path: '/en-US/rewrite',
},
{
locale: 'nl',
path: '/nl/rewrite',
},
]
for (const check of checks) {
const res = await fetchViaHTTP(appPort, check.path, undefined, {
redirect: 'manual',
})
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect($('html').attr('lang')).toBe(check.locale)
expect($('#router-locale').text()).toBe(check.locale)
expect($('#router-pathname').text()).toBe('/another')
expect($('#router-as-path').text()).toBe('/rewrite')
}
})
it('should navigate with locale prop correctly', async () => {
const browser = await webdriver(appPort, '/links?nextLocale=fr')
await addDefaultLocaleCookie(browser)
await browser.eval('window.beforeNav = 1')
if (!isDev) {
await browser.eval(`(function() {
document.querySelector('#to-gsp').scrollIntoView()
document.querySelector('#to-fallback-first').scrollIntoView()
document.querySelector('#to-no-fallback-first').scrollIntoView()
})()`)
await check(async () => {
const hrefs = await browser.eval(`Object.keys(window.next.router.sdc)`)
hrefs.sort()
assert.deepEqual(
hrefs.map((href) =>
new URL(href).pathname.replace(/^\/_next\/data\/[^/]+/, '')
),
[
'/fr/gsp.json',
'/fr/gsp/fallback/first.json',
'/fr/gsp/fallback/hello.json',
]
)
return 'yes'
}, 'yes')
}
expect(await browser.elementByCss('#router-pathname').text()).toBe('/links')
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/links?nextLocale=fr'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ nextLocale: 'fr' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe(
'en-US'
)
await browser.elementByCss('#to-another').click()
await browser.waitForElementByCss('#another')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/another'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/another'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('fr')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({})
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('fr')
let parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe('/fr/another')
expect(parsedUrl.query).toEqual({})
await browser.eval('window.history.back()')
await browser.waitForElementByCss('#links')
expect(await browser.elementByCss('#router-pathname').text()).toBe('/links')
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/links?nextLocale=fr'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ nextLocale: 'fr' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe(
'en-US'
)
parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe('/links')
expect(parsedUrl.query).toEqual({ nextLocale: 'fr' })
await browser.eval('window.history.forward()')
await browser.waitForElementByCss('#another')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/another'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/another'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('fr')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({})
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('fr')
parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe('/fr/another')
expect(parsedUrl.query).toEqual({})
expect(await browser.eval('window.beforeNav')).toBe(1)
expect(await browser.eval('window.caughtWarns')).toEqual([])
})
it('should navigate with locale prop correctly GSP', async () => {
const browser = await webdriver(appPort, '/links?nextLocale=nl')
await addDefaultLocaleCookie(browser)
await browser.eval('window.beforeNav = 1')
expect(await browser.elementByCss('#router-pathname').text()).toBe('/links')
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/links?nextLocale=nl'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ nextLocale: 'nl' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe(
'en-US'
)
await browser.elementByCss('#to-fallback-first').click()
await browser.waitForElementByCss('#gsp')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/gsp/fallback/[slug]'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/gsp/fallback/first'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('nl')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ slug: 'first' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('nl')
let parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe('/nl/gsp/fallback/first')
expect(parsedUrl.query).toEqual({})
await browser.eval('window.history.back()')
await browser.waitForElementByCss('#links')
expect(await browser.elementByCss('#router-pathname').text()).toBe('/links')
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/links?nextLocale=nl'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ nextLocale: 'nl' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe(
'en-US'
)
parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe('/links')
expect(parsedUrl.query).toEqual({ nextLocale: 'nl' })
await browser.eval('window.history.forward()')
await browser.waitForElementByCss('#gsp')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/gsp/fallback/[slug]'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/gsp/fallback/first'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('nl')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ slug: 'first' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('nl')
parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe('/nl/gsp/fallback/first')
expect(parsedUrl.query).toEqual({})
expect(await browser.eval('window.beforeNav')).toBe(1)
expect(await browser.eval('window.caughtWarns')).toEqual([])
})
it('should navigate with locale false correctly', async () => {
const browser = await webdriver(appPort, '/locale-false?nextLocale=fr')
await addDefaultLocaleCookie(browser)
await browser.eval('window.beforeNav = 1')
if (!isDev) {
await browser.eval(`(function() {
document.querySelector('#to-gsp').scrollIntoView()
document.querySelector('#to-fallback-first').scrollIntoView()
document.querySelector('#to-no-fallback-first').scrollIntoView()
})()`)
await check(async () => {
const hrefs = await browser.eval(`Object.keys(window.next.router.sdc)`)
hrefs.sort()
assert.deepEqual(
hrefs.map((href) =>
new URL(href).pathname.replace(/^\/_next\/data\/[^/]+/, '')
),
[
'/fr/gsp.json',
'/fr/gsp/fallback/first.json',
'/fr/gsp/fallback/hello.json',
]
)
return 'yes'
}, 'yes')
}
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/locale-false'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/locale-false?nextLocale=fr'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ nextLocale: 'fr' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe(
'en-US'
)
await browser.elementByCss('#to-another').click()
await browser.waitForElementByCss('#another')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/another'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/another'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('fr')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({})
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('fr')
let parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe('/fr/another')
expect(parsedUrl.query).toEqual({})
await browser.eval('window.history.back()')
await browser.waitForElementByCss('#links')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/locale-false'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/locale-false?nextLocale=fr'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ nextLocale: 'fr' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe(
'en-US'
)
parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe('/locale-false')
expect(parsedUrl.query).toEqual({ nextLocale: 'fr' })
await browser.eval('window.history.forward()')
await browser.waitForElementByCss('#another')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/another'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/another'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('fr')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({})
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('fr')
parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe('/fr/another')
expect(parsedUrl.query).toEqual({})
expect(await browser.eval('window.beforeNav')).toBe(1)
expect(await browser.eval('window.caughtWarns')).toEqual([])
})
it('should navigate with locale false correctly GSP', async () => {
const browser = await webdriver(appPort, '/locale-false?nextLocale=nl')
await addDefaultLocaleCookie(browser)
await browser.eval('window.beforeNav = 1')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/locale-false'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/locale-false?nextLocale=nl'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ nextLocale: 'nl' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe(
'en-US'
)
await browser.elementByCss('#to-fallback-first').click()
await browser.waitForElementByCss('#gsp')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/gsp/fallback/[slug]'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/gsp/fallback/first'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('nl')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ slug: 'first' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('nl')
let parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe('/nl/gsp/fallback/first')
expect(parsedUrl.query).toEqual({})
await browser.eval('window.history.back()')
await browser.waitForElementByCss('#links')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/locale-false'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/locale-false?nextLocale=nl'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ nextLocale: 'nl' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe(
'en-US'
)
parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe('/locale-false')
expect(parsedUrl.query).toEqual({ nextLocale: 'nl' })
await browser.eval('window.history.forward()')
await browser.waitForElementByCss('#gsp')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/gsp/fallback/[slug]'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/gsp/fallback/first'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('nl')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ slug: 'first' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('nl')
parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe('/nl/gsp/fallback/first')
expect(parsedUrl.query).toEqual({})
expect(await browser.eval('window.beforeNav')).toBe(1)
expect(await browser.eval('window.caughtWarns')).toEqual([])
})
it('should update asPath on the client correctly', async () => {
for (const check of ['en', 'En']) {
const browser = await webdriver(appPort, `/${check}`)
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('en')
expect(await browser.elementByCss('#router-locale').text()).toBe('en')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(await browser.elementByCss('#router-as-path').text()).toBe('/')
expect(await browser.elementByCss('#router-pathname').text()).toBe('/')
}
})
if (!isDev) {
it('should handle fallback correctly after generating', async () => {
const browser = await webdriver(
appPort,
'/en/gsp/fallback/hello-fallback'
)
// wait for the fallback to be generated/stored to ISR cache
browser.waitForElementByCss('#gsp')
// now make sure we're serving the previously generated file from the cache
const html = await renderViaHTTP(
appPort,
'/en/gsp/fallback/hello-fallback'
)
const $ = cheerio.load(html)
expect($('#gsp').text()).toBe('gsp page')
expect($('#router-locale').text()).toBe('en')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect($('#router-pathname').text()).toBe('/gsp/fallback/[slug]')
expect($('#router-as-path').text()).toBe('/gsp/fallback/hello-fallback')
})
}
it('should use correct default locale for locale domains', async () => {
const res = await fetchViaHTTP(appPort, '/', undefined, {
headers: {
host: 'example.fr',
},
})
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect($('html').attr('lang')).toBe('fr')
expect($('#router-locale').text()).toBe('fr')
expect($('#router-as-path').text()).toBe('/')
expect($('#router-pathname').text()).toBe('/')
// expect(JSON.parse($('#router-locales').text())).toEqual(['fr','fr-BE'])
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
const res2 = await fetchViaHTTP(appPort, '/', undefined, {
headers: {
host: 'example.be',
},
})
expect(res2.status).toBe(200)
const html2 = await res2.text()
const $2 = cheerio.load(html2)
expect($2('html').attr('lang')).toBe('nl-BE')
expect($2('#router-locale').text()).toBe('nl-BE')
expect($2('#router-as-path').text()).toBe('/')
expect($2('#router-pathname').text()).toBe('/')
// expect(JSON.parse($2('#router-locales').text())).toEqual(['nl-BE','fr-BE'])
expect(JSON.parse($2('#router-locales').text())).toEqual(locales)
})
it('should not strip locale prefix for default locale with locale domains', async () => {
const res = await fetchViaHTTP(appPort, '/fr', undefined, {
headers: {
host: 'example.fr',
},
redirect: 'manual',
})
expect(res.status).toBe(200)
// const result = url.parse(res.headers.get('location'), true)
// expect(result.pathname).toBe('/')
// expect(result.query).toEqual({})
const res2 = await fetchViaHTTP(appPort, '/nl-BE', undefined, {
headers: {
host: 'example.be',
},
redirect: 'manual',
})
expect(res2.status).toBe(200)
// const result2 = url.parse(res2.headers.get('location'), true)
// expect(result2.pathname).toBe('/')
// expect(result2.query).toEqual({})
})
// ('should set locale cookie when removing default locale and accept-lang doesnt match', async () => {
// const res = await fetchViaHTTP(appPort, '/en-US', undefined, {
// headers: {
// 'accept-language': 'nl',
// },
// redirect: 'manual',
// })
// expect(res.status).toBe(307)
// const parsedUrl = url.parse(res.headers.get('location'), true)
// expect(parsedUrl.pathname).toBe('/')
// expect(parsedUrl.query).toEqual({})
// expect(res.headers.get('set-cookie')).toContain('NEXT_LOCALE=en-US')
// })
it('should not redirect to accept-lang preferred locale with locale cookie', async () => {
const res = await fetchViaHTTP(appPort, '/', undefined, {
headers: {
'accept-language': 'nl',
cookie: 'NEXT_LOCALE=en-US',
},
redirect: 'manual',
})
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect($('#router-locale').text()).toBe('en-US')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect($('html').attr('lang')).toBe('en-US')
expect($('#router-pathname').text()).toBe('/')
expect($('#router-as-path').text()).toBe('/')
})
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, locale, location] = check
const res = await fetchViaHTTP(appPort, `/`, undefined, {
headers: {
host: domain,
'accept-language': locale,
},
redirect: 'manual',
})
expect(res.status).toBe(307)
expect(res.headers.get('location')).toBe(location)
}
})
it('should handle locales with domain', async () => {
const domainItems = [
{
// 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'],
},
]
const domainLocales = domainItems.reduce((prev, cur) => {
return [...prev, ...cur.locales]
}, [])
const checkDomainLocales = async (
domainDefault = '',
domain = '',
locale = ''
) => {
const res = await fetchViaHTTP(appPort, `/`, undefined, {
headers: {
host: domain,
'accept-language': locale,
},
redirect: 'manual',
})
const expectedDomainItem = domainItems.find(
(item) => item.defaultLocale === locale || item.locales.includes(locale)
)
const shouldRedirect =
expectedDomainItem.domain !== domain ||
locale !== expectedDomainItem.defaultLocale
expect(res.status).toBe(shouldRedirect ? 307 : 200)
if (shouldRedirect) {
const parsedUrl = url.parse(res.headers.get('location'), true)
expect(parsedUrl.pathname).toBe(
`/${expectedDomainItem.defaultLocale === locale ? '' : locale}`
)
expect(parsedUrl.query).toEqual({})
expect(parsedUrl.hostname).toBe(expectedDomainItem.domain)
} else {
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(locales)
// this will not be the domain's defaultLocale since we don't
// generate a prerendered version for each locale domain currently
expect($('#router-default-locale').text()).toBe('en-US')
}
}
for (const item of domainItems) {
for (const locale of domainLocales) {
await checkDomainLocales(item.defaultLocale, item.domain, locale)
}
}
})
it('should provide correctly defaultLocale for locale domain', async () => {
for (const { host, locale } of [
{ host: 'example.fr', locale: 'fr' },
{ host: 'example.be', locale: 'nl-BE' },
]) {
const res = await fetchViaHTTP(appPort, '/gssp', undefined, {
redirect: 'manual',
headers: {
host,
},
})
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect($('#router-locale').text()).toBe(locale)
expect($('#router-default-locale').text()).toBe(locale)
expect(JSON.parse($('#props').text())).toEqual({
defaultLocale: locale,
locale,
locales,
})
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
}
})
it('should generate AMP pages with all locales', async () => {
for (const locale of locales) {
const localePath = locale !== 'en-US' ? `/${locale}` : ''
const html = await renderViaHTTP(appPort, `${localePath}/amp/amp-hybrid`)
const $ = cheerio.load(html)
expect($('html').attr('lang')).toBe(locale)
expect($('#is-amp').text()).toBe('no')
expect($('#router-locale').text()).toBe(locale)
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect($('#router-pathname').text()).toBe('/amp/amp-hybrid')
expect($('#router-as-path').text()).toBe('/amp/amp-hybrid')
expect(JSON.parse($('#router-query').text())).toEqual({})
const amphtmlPath = `${localePath}/amp/amp-hybrid${
isDev ? '?amp=1' : '.amp'
}`
expect($('link[rel=amphtml]').attr('href')).toBe(amphtmlPath)
const html2 = await renderViaHTTP(appPort, amphtmlPath)
const $2 = cheerio.load(html2)
expect($2('html').attr('lang')).toBe(locale)
expect($2('#is-amp').text()).toBe('yes')
expect($2('#router-locale').text()).toBe(locale)
expect(JSON.parse($2('#router-locales').text())).toEqual(locales)
expect($2('#router-pathname').text()).toBe('/amp/amp-hybrid')
expect($2('#router-as-path').text()).toBe('/amp/amp-hybrid')
expect(JSON.parse($2('#router-query').text())).toEqual({ amp: '1' })
expect($2('link[rel=amphtml]').attr('href')).toBeFalsy()
}
})
it('should work with AMP first page with all locales', async () => {
for (const locale of locales) {
const localePath = locale !== 'en-US' ? `/${locale}` : ''
const html = await renderViaHTTP(appPort, `${localePath}/amp/amp-first`)
const $ = cheerio.load(html)
expect($('html').attr('lang')).toBe(locale)
expect($('#is-amp').text()).toBe('yes')
expect($('#router-locale').text()).toBe(locale)
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect($('#router-pathname').text()).toBe('/amp/amp-first')
expect($('#router-as-path').text()).toBe('/amp/amp-first')
expect(JSON.parse($('#router-query').text())).toEqual({})
expect($('link[rel=amphtml]').attr('href')).toBeFalsy()
}
})
it('should generate fallbacks with all locales', async () => {
for (const locale of locales) {
const html = await renderViaHTTP(
appPort,
`/${locale}/gsp/fallback/${Math.random()}`
)
const $ = cheerio.load(html)
expect($('html').attr('lang')).toBe(locale)
}
})
it('should generate auto-export page with all locales', async () => {
for (const locale of locales) {
const html = await renderViaHTTP(appPort, `/${locale}`)
const $ = cheerio.load(html)
expect($('html').attr('lang')).toBe(locale)
expect($('#router-locale').text()).toBe(locale)
expect($('#router-as-path').text()).toBe('/')
expect($('#router-pathname').text()).toBe('/')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
const html2 = await renderViaHTTP(appPort, `/${locale}/auto-export`)
const $2 = cheerio.load(html2)
expect($2('html').attr('lang')).toBe(locale)
expect($2('#router-locale').text()).toBe(locale)
expect($2('#router-as-path').text()).toBe('/auto-export')
expect($2('#router-pathname').text()).toBe('/auto-export')
expect(JSON.parse($2('#router-locales').text())).toEqual(locales)
}
})
it('should generate non-dynamic GSP page with all locales', async () => {
for (const locale of locales) {
const html = await renderViaHTTP(appPort, `/${locale}/gsp`)
const $ = cheerio.load(html)
expect($('html').attr('lang')).toBe(locale)
expect($('#router-locale').text()).toBe(locale)
expect($('#router-as-path').text()).toBe('/gsp')
expect($('#router-pathname').text()).toBe('/gsp')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
// make sure locale is case-insensitive
const html2 = await renderViaHTTP(appPort, `/${locale.toUpperCase()}/gsp`)
const $2 = cheerio.load(html2)
expect($2('html').attr('lang')).toBe(locale)
expect($2('#router-locale').text()).toBe(locale)
expect($2('#router-as-path').text()).toBe('/gsp')
expect($2('#router-pathname').text()).toBe('/gsp')
expect(JSON.parse($2('#router-locales').text())).toEqual(locales)
}
})
if (!isDev) {
it('should not output GSP pages that returned notFound', async () => {
const skippedLocales = ['en', 'nl']
for (const locale of locales) {
const pagePath = join(buildPagesDir, locale, 'not-found.html')
const dataPath = join(buildPagesDir, locale, 'not-found.json')
console.log(pagePath)
expect(await fs.exists(pagePath)).toBe(!skippedLocales.includes(locale))
expect(await fs.exists(dataPath)).toBe(!skippedLocales.includes(locale))
}
})
}
it('should 404 for GSP pages that returned notFound', async () => {
const skippedLocales = ['en', 'nl']
for (const locale of locales) {
const res = await fetchViaHTTP(appPort, `/${locale}/not-found`)
expect(res.status).toBe(skippedLocales.includes(locale) ? 404 : 200)
if (skippedLocales.includes(locale)) {
const browser = await webdriver(appPort, `/${locale}/not-found`)
expect(await browser.elementByCss('html').getAttribute('lang')).toBe(
locale
)
expect(
await browser.eval('document.documentElement.innerHTML')
).toContain('This page could not be found')
const props = JSON.parse(await browser.elementByCss('#props').text())
expect(props.is404).toBe(true)
expect(props.locale).toBe(locale)
const parsedUrl = url.parse(
await browser.eval('window.location.href'),
true
)
expect(parsedUrl.pathname).toBe(`/${locale}/not-found`)
expect(parsedUrl.query).toEqual({})
}
}
})
it('should transition on client properly for page that starts with locale', async () => {
const browser = await webdriver(appPort, '/fr')
await browser.eval(`(function() {
window.beforeNav = 1
window.next.router.push('/frank')
})()`)
await browser.waitForElementByCss('#frank')
expect(await browser.elementByCss('#router-locale').text()).toBe('fr')
expect(await browser.elementByCss('#router-default-locale').text()).toBe(
'en-US'
)
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({})
expect(await browser.elementByCss('#router-pathname').text()).toBe('/frank')
expect(await browser.elementByCss('#router-as-path').text()).toBe('/frank')
expect(
url.parse(await browser.eval(() => window.location.href)).pathname
).toBe('/fr/frank')
expect(await browser.eval('window.beforeNav')).toBe(1)
})
it('should 404 for GSP that returned notFound on client-transition', async () => {
const browser = await webdriver(appPort, '/en')
await browser.eval(`(function() {
window.beforeNav = 1
window.next.router.push('/not-found')
})()`)
await browser.waitForElementByCss('h1')
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('en')
expect(await browser.elementByCss('html').text()).toContain(
'This page could not be found'
)
const props = JSON.parse(await browser.elementByCss('#props').text())
expect(props.is404).toBe(true)
expect(props.locale).toBe('en')
expect(await browser.eval('window.beforeNav')).toBe(null)
})
it('should render 404 for fallback page that returned 404 on client transition', async () => {
const browser = await webdriver(appPort, '/en', true, true)
await browser.eval(`(function() {
next.router.push('/not-found/fallback/first')
})()`)
await browser.waitForElementByCss('h1')
await browser.eval('window.beforeNav = 1')
expect(await browser.elementByCss('html').text()).toContain(
'This page could not be found'
)
const props = JSON.parse(await browser.elementByCss('#props').text())
expect(props.is404).toBe(true)
expect(props.locale).toBe('en')
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('en')
const parsedUrl = url.parse(
await browser.eval('window.location.href'),
true
)
expect(parsedUrl.pathname).toBe('/en/not-found/fallback/first')
expect(parsedUrl.query).toEqual({})
if (isDev) {
// make sure page doesn't reload un-necessarily in development
await waitFor(10 * 1000)
}
expect(await browser.eval('window.beforeNav')).toBe(1)
})
it('should render 404 for fallback page that returned 404', async () => {
const browser = await webdriver(
appPort,
'/en/not-found/fallback/first',
true,
true
)
await browser.waitForElementByCss('h1')
await browser.eval('window.beforeNav = 1')
expect(await browser.elementByCss('html').text()).toContain(
'This page could not be found'
)
const props = JSON.parse(await browser.elementByCss('#props').text())
expect(props.is404).toBe(true)
expect(props.locale).toBe('en')
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('en')
const parsedUrl = url.parse(
await browser.eval('window.location.href'),
true
)
expect(parsedUrl.pathname).toBe('/en/not-found/fallback/first')
expect(parsedUrl.query).toEqual({})
if (isDev) {
// make sure page doesn't reload un-necessarily in development
await waitFor(10 * 1000)
}
expect(await browser.eval('window.beforeNav')).toBe(1)
})
it('should render 404 for blocking fallback page that returned 404 on client transition', async () => {
const browser = await webdriver(appPort, '/en', true, true)
await browser.eval(`(function() {
next.router.push('/not-found/blocking-fallback/first')
})()`)
await browser.waitForElementByCss('h1')
await browser.eval('window.beforeNav = 1')
expect(await browser.elementByCss('html').text()).toContain(
'This page could not be found'
)
const props = JSON.parse(await browser.elementByCss('#props').text())
expect(props.is404).toBe(true)
expect(props.locale).toBe('en')
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('en')
const parsedUrl = url.parse(
await browser.eval('window.location.href'),
true
)
expect(parsedUrl.pathname).toBe('/en/not-found/blocking-fallback/first')
expect(parsedUrl.query).toEqual({})
if (isDev) {
// make sure page doesn't reload un-necessarily in development
await waitFor(10 * 1000)
}
expect(await browser.eval('window.beforeNav')).toBe(1)
})
it('should render 404 for blocking fallback page that returned 404', async () => {
const browser = await webdriver(
appPort,
'/en/not-found/blocking-fallback/first',
true,
true
)
await browser.waitForElementByCss('h1')
await browser.eval('window.beforeNav = 1')
expect(await browser.elementByCss('html').text()).toContain(
'This page could not be found'
)
const props = JSON.parse(await browser.elementByCss('#props').text())
expect(props.is404).toBe(true)
expect(props.locale).toBe('en')
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('en')
const parsedUrl = url.parse(
await browser.eval('window.location.href'),
true
)
expect(parsedUrl.pathname).toBe('/en/not-found/blocking-fallback/first')
expect(parsedUrl.query).toEqual({})
if (isDev) {
// make sure page doesn't reload un-necessarily in development
await waitFor(10 * 1000)
}
expect(await browser.eval('window.beforeNav')).toBe(1)
})
it('should not remove locale prefix for default locale', async () => {
const res = await fetchViaHTTP(appPort, '/en-US', undefined, {
redirect: 'manual',
headers: {
'Accept-Language': 'en-US;q=0.9',
},
})
expect(res.status).toBe(200)
// const parsedUrl = url.parse(res.headers.get('location'), true)
// expect(parsedUrl.pathname).toBe('/')
// expect(parsedUrl.query).toEqual({})
// make sure locale is case-insensitive
const res2 = await fetchViaHTTP(appPort, '/eN-Us', undefined, {
redirect: 'manual',
headers: {
'Accept-Language': 'en-US;q=0.9',
},
})
expect(res2.status).toBe(200)
// const parsedUrl2 = url.parse(res.headers.get('location'), true)
// expect(parsedUrl2.pathname).toBe('/')
// expect(parsedUrl2.query).toEqual({})
})
it('should load getStaticProps page correctly SSR (default locale no prefix)', async () => {
const html = await renderViaHTTP(appPort, '/gsp')
const $ = cheerio.load(html)
expect(JSON.parse($('#props').text())).toEqual({
locale: 'en-US',
locales,
defaultLocale: 'en-US',
})
expect($('#router-locale').text()).toBe('en-US')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect($('html').attr('lang')).toBe('en-US')
})
it('should load getStaticProps fallback prerender page correctly SSR (default locale no prefix)', async () => {
const html = await renderViaHTTP(appPort, '/gsp/fallback/first')
const $ = cheerio.load(html)
expect(JSON.parse($('#props').text())).toEqual({
locale: 'en-US',
locales,
params: {
slug: 'first',
},
defaultLocale: 'en-US',
})
expect(JSON.parse($('#router-query').text())).toEqual({
slug: 'first',
})
expect($('#router-locale').text()).toBe('en-US')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect($('html').attr('lang')).toBe('en-US')
})
it('should load getStaticProps fallback non-prerender page correctly (default locale no prefix', async () => {
const browser = await webdriver(appPort, '/gsp/fallback/another')
await browser.waitForElementByCss('#props')
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
locale: 'en-US',
locales,
params: {
slug: 'another',
},
defaultLocale: 'en-US',
})
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({
slug: 'another',
})
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
})
it('should redirect to locale prefixed route for /', async () => {
const res = await fetchViaHTTP(appPort, '/', undefined, {
redirect: 'manual',
headers: {
'Accept-Language': 'nl-NL,nl;q=0.9,en-US;q=0.8,en;q=0.7',
},
})
expect(res.status).toBe(307)
const parsedUrl = url.parse(res.headers.get('location'), true)
expect(parsedUrl.pathname).toBe('/nl-NL')
expect(parsedUrl.query).toEqual({})
const res2 = await fetchViaHTTP(
appPort,
'/',
{ hello: 'world' },
{
redirect: 'manual',
headers: {
'Accept-Language': 'en;q=0.9',
},
}
)
expect(res2.status).toBe(307)
const parsedUrl2 = url.parse(res2.headers.get('location'), true)
expect(parsedUrl2.pathname).toBe('/en')
expect(parsedUrl2.query).toEqual({ hello: 'world' })
})
it('should use default locale for / without accept-language', async () => {
const res = await fetchViaHTTP(appPort, '/', undefined, {
redirect: 'manual',
})
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect($('#router-locale').text()).toBe('en-US')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect(JSON.parse($('#router-query').text())).toEqual({})
expect($('#router-pathname').text()).toBe('/')
expect($('#router-as-path').text()).toBe('/')
const res2 = await fetchViaHTTP(
appPort,
'/',
{ hello: 'world' },
{
redirect: 'manual',
}
)
expect(res2.status).toBe(200)
const html2 = await res2.text()
const $2 = cheerio.load(html2)
expect($2('#router-locale').text()).toBe('en-US')
expect(JSON.parse($2('#router-locales').text())).toEqual(locales)
// page is auto-export so query isn't hydrated until client
expect(JSON.parse($2('#router-query').text())).toEqual({})
expect($2('#router-pathname').text()).toBe('/')
// expect($2('#router-as-path').text()).toBe('/')
})
it('should load getStaticProps page correctly SSR', async () => {
const html = await renderViaHTTP(appPort, '/en-US/gsp')
const $ = cheerio.load(html)
expect(JSON.parse($('#props').text())).toEqual({
locale: 'en-US',
locales,
defaultLocale: 'en-US',
})
expect($('#router-locale').text()).toBe('en-US')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect($('html').attr('lang')).toBe('en-US')
})
it('should load getStaticProps fallback prerender page correctly SSR', async () => {
const html = await renderViaHTTP(appPort, '/en-US/gsp/fallback/first')
const $ = cheerio.load(html)
expect(JSON.parse($('#props').text())).toEqual({
locale: 'en-US',
locales,
params: {
slug: 'first',
},
defaultLocale: 'en-US',
})
expect(JSON.parse($('#router-query').text())).toEqual({
slug: 'first',
})
expect($('#router-locale').text()).toBe('en-US')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect($('html').attr('lang')).toBe('en-US')
})
it('should load getStaticProps fallback non-prerender page correctly', async () => {
const browser = await webdriver(appPort, '/en/gsp/fallback/another')
await browser.waitForElementByCss('#props')
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
locale: 'en',
locales,
params: {
slug: 'another',
},
defaultLocale: 'en-US',
})
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({
slug: 'another',
})
expect(await browser.elementByCss('#router-locale').text()).toBe('en')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('en')
})
it('should load getServerSideProps page correctly SSR (default locale no prefix)', async () => {
const html = await renderViaHTTP(appPort, '/gssp')
const $ = cheerio.load(html)
expect(JSON.parse($('#props').text())).toEqual({
locale: 'en-US',
locales,
defaultLocale: 'en-US',
})
expect($('#router-locale').text()).toBe('en-US')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect(JSON.parse($('#router-query').text())).toEqual({})
expect($('html').attr('lang')).toBe('en-US')
})
it('should navigate client side for default locale with no prefix', async () => {
const browser = await webdriver(appPort, '/')
await addDefaultLocaleCookie(browser)
const checkIndexValues = async () => {
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({})
expect(await browser.elementByCss('#router-pathname').text()).toBe('/')
expect(await browser.elementByCss('#router-as-path').text()).toBe('/')
expect(
url.parse(await browser.eval(() => window.location.href)).pathname
).toBe('/')
}
await checkIndexValues()
await browser.elementByCss('#to-another').click()
await browser.waitForElementByCss('#another')
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
locale: 'en-US',
locales,
defaultLocale: 'en-US',
})
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({})
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/another'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/another'
)
expect(
url.parse(await browser.eval(() => window.location.href)).pathname
).toBe('/another')
await browser.elementByCss('#to-index').click()
await browser.waitForElementByCss('#index')
await checkIndexValues()
await browser.elementByCss('#to-gsp').click()
await browser.waitForElementByCss('#gsp')
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
locale: 'en-US',
locales,
defaultLocale: 'en-US',
})
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({})
expect(await browser.elementByCss('#router-pathname').text()).toBe('/gsp')
expect(await browser.elementByCss('#router-as-path').text()).toBe('/gsp')
expect(
url.parse(await browser.eval(() => window.location.href)).pathname
).toBe('/gsp')
await browser.elementByCss('#to-index').click()
await browser.waitForElementByCss('#index')
await checkIndexValues()
await browser.manage().deleteCookie('NEXT_LOCALE')
})
it('should load getStaticProps fallback non-prerender page another locale correctly', async () => {
const browser = await webdriver(appPort, '/nl-NL/gsp/fallback/another')
await browser.waitForElementByCss('#props')
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
locale: 'nl-NL',
locales,
params: {
slug: 'another',
},
defaultLocale: 'en-US',
})
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({
slug: 'another',
})
expect(await browser.elementByCss('#router-locale').text()).toBe('nl-NL')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
})
it('should load getStaticProps non-fallback correctly', async () => {
const browser = await webdriver(appPort, '/en-US/gsp/no-fallback/first')
await browser.waitForElementByCss('#props')
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
locale: 'en-US',
locales,
params: {
slug: 'first',
},
defaultLocale: 'en-US',
})
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({
slug: 'first',
})
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(await browser.elementByCss('html').getAttribute('lang')).toBe(
'en-US'
)
})
it('should load getStaticProps non-fallback correctly another locale', async () => {
const browser = await webdriver(appPort, '/nl-NL/gsp/no-fallback/second')
await browser.waitForElementByCss('#props')
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
locale: 'nl-NL',
locales,
params: {
slug: 'second',
},
defaultLocale: 'en-US',
})
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({
slug: 'second',
})
expect(await browser.elementByCss('#router-locale').text()).toBe('nl-NL')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(await browser.elementByCss('html').getAttribute('lang')).toBe(
'nl-NL'
)
})
it('should load getStaticProps non-fallback correctly another locale via cookie', async () => {
const html = await renderViaHTTP(
appPort,
'/nl-NL/gsp/no-fallback/second',
{},
{
headers: {
cookie: 'NEXT_LOCALE=nl-NL',
},
}
)
const $ = cheerio.load(html)
expect(JSON.parse($('#props').text())).toEqual({
locale: 'nl-NL',
locales,
params: {
slug: 'second',
},
defaultLocale: 'en-US',
})
expect(JSON.parse($('#router-query').text())).toEqual({
slug: 'second',
})
expect($('#router-locale').text()).toBe('nl-NL')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect($('html').attr('lang')).toBe('nl-NL')
})
it('should load getServerSideProps page correctly SSR', async () => {
const html = await renderViaHTTP(appPort, '/en-US/gssp')
const $ = cheerio.load(html)
expect(JSON.parse($('#props').text())).toEqual({
locale: 'en-US',
locales,
defaultLocale: 'en-US',
})
expect($('#router-locale').text()).toBe('en-US')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect(JSON.parse($('#router-query').text())).toEqual({})
expect($('html').attr('lang')).toBe('en-US')
const html2 = await renderViaHTTP(appPort, '/nl-NL/gssp')
const $2 = cheerio.load(html2)
expect(JSON.parse($2('#props').text())).toEqual({
locale: 'nl-NL',
locales,
defaultLocale: 'en-US',
})
expect($2('#router-locale').text()).toBe('nl-NL')
expect(JSON.parse($2('#router-locales').text())).toEqual(locales)
expect(JSON.parse($2('#router-query').text())).toEqual({})
expect($2('html').attr('lang')).toBe('nl-NL')
})
it('should load dynamic getServerSideProps page correctly SSR', async () => {
const html = await renderViaHTTP(appPort, '/en-US/gssp/first')
const $ = cheerio.load(html)
expect(JSON.parse($('#props').text())).toEqual({
locale: 'en-US',
locales,
params: {
slug: 'first',
},
defaultLocale: 'en-US',
})
expect($('#router-locale').text()).toBe('en-US')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect(JSON.parse($('#router-query').text())).toEqual({ slug: 'first' })
expect($('html').attr('lang')).toBe('en-US')
const html2 = await renderViaHTTP(appPort, '/nl-NL/gssp/first')
const $2 = cheerio.load(html2)
expect(JSON.parse($2('#props').text())).toEqual({
locale: 'nl-NL',
locales,
params: {
slug: 'first',
},
defaultLocale: 'en-US',
})
expect($2('#router-locale').text()).toBe('nl-NL')
expect(JSON.parse($2('#router-locales').text())).toEqual(locales)
expect(JSON.parse($2('#router-query').text())).toEqual({ slug: 'first' })
expect($2('html').attr('lang')).toBe('nl-NL')
})
it('should navigate to another page and back correctly with locale', async () => {
const browser = await webdriver(appPort, '/en')
await browser.eval('window.beforeNav = "hi"')
await browser
.elementByCss('#to-another')
.click()
.waitForElementByCss('#another')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/another'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/another'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('en')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
locale: 'en',
locales,
defaultLocale: 'en-US',
})
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({})
expect(await browser.eval('window.beforeNav')).toBe('hi')
await browser.back().waitForElementByCss('#index')
expect(await browser.eval('window.beforeNav')).toBe('hi')
expect(await browser.elementByCss('#router-pathname').text()).toBe('/')
expect(await browser.elementByCss('#router-as-path').text()).toBe('/')
})
it('should navigate to getStaticProps page and back correctly with locale', async () => {
const browser = await webdriver(appPort, '/en')
await browser.eval('window.beforeNav = "hi"')
await browser.elementByCss('#to-gsp').click().waitForElementByCss('#gsp')
expect(await browser.elementByCss('#router-pathname').text()).toBe('/gsp')
expect(await browser.elementByCss('#router-as-path').text()).toBe('/gsp')
expect(await browser.elementByCss('#router-locale').text()).toBe('en')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
locale: 'en',
locales,
defaultLocale: 'en-US',
})
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({})
expect(await browser.eval('window.beforeNav')).toBe('hi')
await browser.back().waitForElementByCss('#index')
expect(await browser.eval('window.beforeNav')).toBe('hi')
expect(await browser.elementByCss('#router-pathname').text()).toBe('/')
expect(await browser.elementByCss('#router-as-path').text()).toBe('/')
})
} }
describe('i18n Support', () => { describe('i18n Support', () => {
// TODO: test with next export?
describe('dev mode', () => { describe('dev mode', () => {
const curCtx = {
...ctx,
isDev: true,
}
beforeAll(async () => { beforeAll(async () => {
await fs.remove(join(appDir, '.next')) await fs.remove(join(appDir, '.next'))
appPort = await findPort() curCtx.appPort = await findPort()
app = await launchApp(appDir, appPort) curCtx.app = await launchApp(appDir, curCtx.appPort)
// buildId = 'development' })
afterAll(async () => {
await killApp(curCtx.app)
}) })
afterAll(() => killApp(app))
runTests(true) runTests(curCtx)
}) })
describe('production mode', () => { describe('production mode', () => {
beforeAll(async () => { beforeAll(async () => {
await fs.remove(join(appDir, '.next')) await fs.remove(join(appDir, '.next'))
await nextBuild(appDir) await nextBuild(appDir)
appPort = await findPort() ctx.appPort = await findPort()
app = await nextStart(appDir, appPort) ctx.app = await nextStart(appDir, ctx.appPort)
buildPagesDir = join(appDir, '.next/server/pages') ctx.buildPagesDir = join(appDir, '.next/server/pages')
buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8') ctx.buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
}) })
afterAll(() => killApp(app)) afterAll(() => killApp(ctx.app))
runTests() runTests(ctx)
}) })
describe('serverless mode', () => { describe('serverless mode', () => {
...@@ -1947,14 +59,14 @@ describe('i18n Support', () => { ...@@ -1947,14 +59,14 @@ describe('i18n Support', () => {
nextConfig.replace('// target', 'target') nextConfig.replace('// target', 'target')
await nextBuild(appDir) await nextBuild(appDir)
appPort = await findPort() ctx.appPort = await findPort()
app = await nextStart(appDir, appPort) ctx.app = await nextStart(appDir, ctx.appPort)
buildPagesDir = join(appDir, '.next/serverless/pages') ctx.buildPagesDir = join(appDir, '.next/serverless/pages')
buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8') ctx.buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
}) })
afterAll(async () => { afterAll(async () => {
nextConfig.restore() nextConfig.restore()
await killApp(app) await killApp(ctx.app)
}) })
it('should have correct props for blocking notFound', async () => { it('should have correct props for blocking notFound', async () => {
...@@ -1999,7 +111,7 @@ describe('i18n Support', () => { ...@@ -1999,7 +111,7 @@ describe('i18n Support', () => {
}) })
}) })
runTests() runTests(ctx)
}) })
describe('with localeDetection disabled', () => { describe('with localeDetection disabled', () => {
...@@ -2008,12 +120,12 @@ describe('i18n Support', () => { ...@@ -2008,12 +120,12 @@ describe('i18n Support', () => {
nextConfig.replace('// localeDetection', 'localeDetection') nextConfig.replace('// localeDetection', 'localeDetection')
await nextBuild(appDir) await nextBuild(appDir)
appPort = await findPort() ctx.appPort = await findPort()
app = await nextStart(appDir, appPort) ctx.app = await nextStart(appDir, ctx.appPort)
}) })
afterAll(async () => { afterAll(async () => {
nextConfig.restore() nextConfig.restore()
await killApp(app) await killApp(ctx.app)
}) })
it('should have localeDetection in routes-manifest', async () => { it('should have localeDetection in routes-manifest', async () => {
...@@ -2044,7 +156,7 @@ describe('i18n Support', () => { ...@@ -2044,7 +156,7 @@ describe('i18n Support', () => {
it('should not detect locale from accept-language', async () => { it('should not detect locale from accept-language', async () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
appPort, ctx.appPort,
'/', '/',
{}, {},
{ {
...@@ -2067,7 +179,7 @@ describe('i18n Support', () => { ...@@ -2067,7 +179,7 @@ describe('i18n Support', () => {
it('should set locale from detected path', async () => { it('should set locale from detected path', async () => {
for (const locale of locales) { for (const locale of locales) {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
appPort, ctx.appPort,
`/${locale}`, `/${locale}`,
{}, {},
{ {
......
/* eslint-env jest */
import url from 'url'
import fs from 'fs-extra'
import cheerio from 'cheerio'
import { join } from 'path'
import webdriver from 'next-webdriver'
import escapeRegex from 'escape-string-regexp'
import assert from 'assert'
import {
fetchViaHTTP,
renderViaHTTP,
waitFor,
normalizeRegEx,
check,
} from 'next-test-utils'
jest.setTimeout(1000 * 60 * 2)
export const locales = ['en-US', 'nl-NL', 'nl-BE', 'nl', 'fr-BE', 'fr', 'en']
async function addDefaultLocaleCookie(browser) {
// make sure default locale is used in case browser isn't set to
// favor en-US by default, (we use all caps to ensure it's case-insensitive)
await browser.manage().addCookie({ name: 'NEXT_LOCALE', value: 'EN-US' })
await browser.get(browser.initUrl)
}
export function runTests(ctx) {
if (ctx.isDev) {
it('should show error for redirect and notFound returned at same time', async () => {
const html = await renderViaHTTP(
ctx.appPort,
`${ctx.basePath}/_next/data/development/gsp/fallback/mixed-not-found-redirect.json`
)
expect(html).toContain(
'`redirect` and `notFound` can not both be returned from getStaticProps at the same time. Page: /gsp/fallback/[slug]'
)
})
}
it('should have correct values for non-prefixed path', async () => {
for (const paths of [
['/links', '/links'],
['/another', '/another'],
['/gsp/fallback/first', '/gsp/fallback/[slug]'],
['/gsp/no-fallback/first', '/gsp/no-fallback/[slug]'],
]) {
const [asPath, pathname] = paths
const res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath}${asPath}`,
undefined,
{
redirect: 'manual',
headers: {
'accept-language': 'fr',
},
}
)
expect(res.status).toBe(200)
const $ = cheerio.load(await res.text())
expect($('html').attr('lang')).toBe('en-US')
expect($('#router-locale').text()).toBe('en-US')
expect($('#router-default-locale').text()).toBe('en-US')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect($('#router-pathname').text()).toBe(pathname)
expect($('#router-as-path').text()).toBe(asPath)
}
})
it('should not have hydration mis-match from hash', async () => {
const browser = await webdriver(ctx.appPort, `${ctx.basePath}/en#`)
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('en')
expect(await browser.elementByCss('#router-locale').text()).toBe('en')
expect(await browser.elementByCss('#router-default-locale').text()).toBe(
'en-US'
)
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(await browser.elementByCss('#router-pathname').text()).toBe('/')
expect(await browser.elementByCss('#router-as-path').text()).toBe('/')
expect(await browser.eval('window.caughtWarns')).toEqual([])
})
if (!ctx.isDev) {
it('should add i18n config to routes-manifest', async () => {
const routesManifest = await fs.readJSON(
join(ctx.appDir, '.next/routes-manifest.json')
)
expect(routesManifest.i18n).toEqual({
locales: ['en-US', 'nl-NL', 'nl-BE', 'nl', 'fr-BE', 'fr', 'en'],
defaultLocale: 'en-US',
domains: [
{
http: true,
domain: 'example.be',
defaultLocale: 'nl-BE',
locales: ['nl', 'nl-NL', 'nl-BE'],
},
{
http: true,
domain: 'example.fr',
defaultLocale: 'fr',
locales: ['fr-BE'],
},
],
})
})
it('should output correct prerender-manifest', async () => {
const prerenderManifest = await fs.readJSON(
join(ctx.appDir, '.next/prerender-manifest.json')
)
for (const key of Object.keys(prerenderManifest.dynamicRoutes)) {
const item = prerenderManifest.dynamicRoutes[key]
item.routeRegex = normalizeRegEx(item.routeRegex)
item.dataRouteRegex = normalizeRegEx(item.dataRouteRegex)
}
expect(prerenderManifest.routes).toEqual({
'/': {
dataRoute: `/_next/data/${ctx.buildId}/index.json`,
initialRevalidateSeconds: false,
srcRoute: null,
},
'/404': {
dataRoute: `/_next/data/${ctx.buildId}/404.json`,
initialRevalidateSeconds: false,
srcRoute: null,
},
'/en-US/gsp/fallback/first': {
dataRoute: `/_next/data/${ctx.buildId}/en-US/gsp/fallback/first.json`,
initialRevalidateSeconds: false,
srcRoute: '/gsp/fallback/[slug]',
},
'/en-US/gsp/fallback/second': {
dataRoute: `/_next/data/${ctx.buildId}/en-US/gsp/fallback/second.json`,
initialRevalidateSeconds: false,
srcRoute: '/gsp/fallback/[slug]',
},
'/en-US/gsp/no-fallback/first': {
dataRoute: `/_next/data/${ctx.buildId}/en-US/gsp/no-fallback/first.json`,
initialRevalidateSeconds: false,
srcRoute: '/gsp/no-fallback/[slug]',
},
'/en-US/gsp/no-fallback/second': {
dataRoute: `/_next/data/${ctx.buildId}/en-US/gsp/no-fallback/second.json`,
initialRevalidateSeconds: false,
srcRoute: '/gsp/no-fallback/[slug]',
},
'/en-US/not-found/blocking-fallback/first': {
dataRoute: `/_next/data/${ctx.buildId}/en-US/not-found/blocking-fallback/first.json`,
initialRevalidateSeconds: false,
srcRoute: '/not-found/blocking-fallback/[slug]',
},
'/en-US/not-found/blocking-fallback/second': {
dataRoute: `/_next/data/${ctx.buildId}/en-US/not-found/blocking-fallback/second.json`,
initialRevalidateSeconds: false,
srcRoute: '/not-found/blocking-fallback/[slug]',
},
'/en-US/not-found/fallback/first': {
dataRoute: `/_next/data/${ctx.buildId}/en-US/not-found/fallback/first.json`,
initialRevalidateSeconds: false,
srcRoute: '/not-found/fallback/[slug]',
},
'/en-US/not-found/fallback/second': {
dataRoute: `/_next/data/${ctx.buildId}/en-US/not-found/fallback/second.json`,
initialRevalidateSeconds: false,
srcRoute: '/not-found/fallback/[slug]',
},
'/frank': {
dataRoute: `/_next/data/${ctx.buildId}/frank.json`,
initialRevalidateSeconds: false,
srcRoute: null,
},
'/gsp': {
dataRoute: `/_next/data/${ctx.buildId}/gsp.json`,
srcRoute: null,
initialRevalidateSeconds: false,
},
'/nl-NL/gsp/no-fallback/second': {
dataRoute: `/_next/data/${ctx.buildId}/nl-NL/gsp/no-fallback/second.json`,
initialRevalidateSeconds: false,
srcRoute: '/gsp/no-fallback/[slug]',
},
'/not-found': {
dataRoute: `/_next/data/${ctx.buildId}/not-found.json`,
srcRoute: null,
initialRevalidateSeconds: false,
},
})
expect(prerenderManifest.dynamicRoutes).toEqual({
'/gsp/fallback/[slug]': {
routeRegex: normalizeRegEx(
'^\\/gsp\\/fallback\\/([^\\/]+?)(?:\\/)?$'
),
dataRoute: `/_next/data/${ctx.buildId}/gsp/fallback/[slug].json`,
fallback: '/gsp/fallback/[slug].html',
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
ctx.buildId
)}\\/gsp\\/fallback\\/([^\\/]+?)\\.json$`
),
},
'/gsp/no-fallback/[slug]': {
routeRegex: normalizeRegEx(
'^\\/gsp\\/no\\-fallback\\/([^\\/]+?)(?:\\/)?$'
),
dataRoute: `/_next/data/${ctx.buildId}/gsp/no-fallback/[slug].json`,
fallback: false,
dataRouteRegex: normalizeRegEx(
`^/_next/data/${escapeRegex(
ctx.buildId
)}/gsp/no\\-fallback/([^/]+?)\\.json$`
),
},
'/not-found/blocking-fallback/[slug]': {
dataRoute: `/_next/data/${ctx.buildId}/not-found/blocking-fallback/[slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
ctx.buildId
)}\\/not\\-found\\/blocking\\-fallback\\/([^\\/]+?)\\.json$`
),
fallback: null,
routeRegex: normalizeRegEx(
`^\\/not\\-found\\/blocking\\-fallback\\/([^\\/]+?)(?:\\/)?$`
),
},
'/not-found/fallback/[slug]': {
dataRoute: `/_next/data/${ctx.buildId}/not-found/fallback/[slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
ctx.buildId
)}\\/not\\-found\\/fallback\\/([^\\/]+?)\\.json$`
),
fallback: '/not-found/fallback/[slug].html',
routeRegex: normalizeRegEx('^/not\\-found/fallback/([^/]+?)(?:/)?$'),
},
})
})
}
it('should resolve auto-export dynamic route correctly', async () => {
for (const locale of locales) {
const res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath}/${locale}/dynamic/first`,
undefined,
{
redirect: 'manual',
}
)
expect(res.status).toBe(200)
expect(await res.text()).toContain('dynamic page')
}
})
it('should navigate to auto-export dynamic page', async () => {
for (const locale of locales) {
const browser = await webdriver(ctx.appPort, `${ctx.basePath}/${locale}`)
await browser.eval('window.beforeNav = 1')
await browser
.elementByCss('#to-dynamic')
.click()
.waitForElementByCss('#dynamic')
expect(await browser.eval('window.beforeNav')).toBe(1)
expect(await browser.elementByCss('#router-locale').text()).toBe(locale)
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ slug: 'first' })
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/dynamic/[slug]'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/dynamic/first'
)
expect(await browser.eval('window.location.pathname')).toBe(
`${
locale === 'en-US' ? `${ctx.basePath}` : `${ctx.basePath}/${locale}`
}/dynamic/first`
)
await browser.back().waitForElementByCss('#index')
expect(await browser.eval('window.beforeNav')).toBe(1)
expect(await browser.elementByCss('#router-locale').text()).toBe(locale)
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({})
expect(await browser.elementByCss('#router-pathname').text()).toBe('/')
expect(await browser.elementByCss('#router-as-path').text()).toBe('/')
}
})
it('should apply redirects correctly', async () => {
for (const path of ['/redirect', '/en-US/redirect', '/nl/redirect']) {
const res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath}${path}`,
undefined,
{
redirect: 'manual',
}
)
expect(res.status).toBe(307)
const parsed = url.parse(res.headers.get('location'), true)
expect(parsed.pathname).toBe(`${ctx.basePath}/somewhere-else`)
expect(parsed.query).toEqual({})
}
})
it('should apply headers correctly', async () => {
for (const path of ['/add-header', '/en-US/add-header', '/nl/add-header']) {
const res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath}${path}`,
undefined,
{
redirect: 'manual',
}
)
expect(res.status).toBe(404)
expect(res.headers.get('x-hello')).toBe('world')
}
})
it('should apply rewrites correctly', async () => {
const checks = [
{
locale: 'en-US',
path: '/rewrite',
},
{
locale: 'en-US',
path: '/en-US/rewrite',
},
{
locale: 'nl',
path: '/nl/rewrite',
},
]
for (const check of checks) {
const res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath}${check.path}`,
undefined,
{
redirect: 'manual',
}
)
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect($('html').attr('lang')).toBe(check.locale)
expect($('#router-locale').text()).toBe(check.locale)
expect($('#router-pathname').text()).toBe('/another')
expect($('#router-as-path').text()).toBe('/rewrite')
}
})
it('should navigate with locale prop correctly', async () => {
const browser = await webdriver(
ctx.appPort,
`${ctx.basePath}/links?nextLocale=fr`
)
await addDefaultLocaleCookie(browser)
await browser.eval('window.beforeNav = 1')
if (!ctx.isDev) {
await browser.eval(`(function() {
document.querySelector('#to-gsp').scrollIntoView()
document.querySelector('#to-fallback-first').scrollIntoView()
document.querySelector('#to-no-fallback-first').scrollIntoView()
})()`)
await check(async () => {
const hrefs = await browser.eval(`Object.keys(window.next.router.sdc)`)
hrefs.sort()
assert.deepEqual(
hrefs.map((href) =>
new URL(href).pathname
.replace(ctx.basePath, '')
.replace(/^\/_next\/data\/[^/]+/, '')
),
[
'/fr/gsp.json',
'/fr/gsp/fallback/first.json',
'/fr/gsp/fallback/hello.json',
]
)
return 'yes'
}, 'yes')
}
expect(await browser.elementByCss('#router-pathname').text()).toBe('/links')
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/links?nextLocale=fr'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ nextLocale: 'fr' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe(
'en-US'
)
await browser.elementByCss('#to-another').click()
await browser.waitForElementByCss('#another')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/another'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/another'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('fr')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({})
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('fr')
let parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe(`${ctx.basePath}/fr/another`)
expect(parsedUrl.query).toEqual({})
await browser.eval('window.history.back()')
await browser.waitForElementByCss('#links')
expect(await browser.elementByCss('#router-pathname').text()).toBe('/links')
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/links?nextLocale=fr'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ nextLocale: 'fr' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe(
'en-US'
)
parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe(`${ctx.basePath}/links`)
expect(parsedUrl.query).toEqual({ nextLocale: 'fr' })
await browser.eval('window.history.forward()')
await browser.waitForElementByCss('#another')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/another'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/another'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('fr')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({})
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('fr')
parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe(`${ctx.basePath}/fr/another`)
expect(parsedUrl.query).toEqual({})
expect(await browser.eval('window.beforeNav')).toBe(1)
expect(await browser.eval('window.caughtWarns')).toEqual([])
})
it('should navigate with locale prop correctly GSP', async () => {
const browser = await webdriver(
ctx.appPort,
`${ctx.basePath}/links?nextLocale=nl`
)
await addDefaultLocaleCookie(browser)
await browser.eval('window.beforeNav = 1')
expect(await browser.elementByCss('#router-pathname').text()).toBe('/links')
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/links?nextLocale=nl'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ nextLocale: 'nl' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe(
'en-US'
)
await browser.elementByCss('#to-fallback-first').click()
await browser.waitForElementByCss('#gsp')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/gsp/fallback/[slug]'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/gsp/fallback/first'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('nl')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ slug: 'first' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('nl')
let parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe(`${ctx.basePath}/nl/gsp/fallback/first`)
expect(parsedUrl.query).toEqual({})
await browser.eval('window.history.back()')
await browser.waitForElementByCss('#links')
expect(await browser.elementByCss('#router-pathname').text()).toBe('/links')
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/links?nextLocale=nl'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ nextLocale: 'nl' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe(
'en-US'
)
parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe(`${ctx.basePath}/links`)
expect(parsedUrl.query).toEqual({ nextLocale: 'nl' })
await browser.eval('window.history.forward()')
await browser.waitForElementByCss('#gsp')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/gsp/fallback/[slug]'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/gsp/fallback/first'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('nl')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ slug: 'first' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('nl')
parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe(`${ctx.basePath}/nl/gsp/fallback/first`)
expect(parsedUrl.query).toEqual({})
expect(await browser.eval('window.beforeNav')).toBe(1)
expect(await browser.eval('window.caughtWarns')).toEqual([])
})
it('should navigate with locale false correctly', async () => {
const browser = await webdriver(
ctx.appPort,
`${ctx.basePath}/locale-false?nextLocale=fr`
)
await addDefaultLocaleCookie(browser)
await browser.eval('window.beforeNav = 1')
if (!ctx.isDev) {
await browser.eval(`(function() {
document.querySelector('#to-gsp').scrollIntoView()
document.querySelector('#to-fallback-first').scrollIntoView()
document.querySelector('#to-no-fallback-first').scrollIntoView()
})()`)
await check(async () => {
const hrefs = await browser.eval(`Object.keys(window.next.router.sdc)`)
hrefs.sort()
assert.deepEqual(
hrefs.map((href) =>
new URL(href).pathname
.replace(ctx.basePath, '')
.replace(/^\/_next\/data\/[^/]+/, '')
),
[
'/fr/gsp.json',
'/fr/gsp/fallback/first.json',
'/fr/gsp/fallback/hello.json',
]
)
return 'yes'
}, 'yes')
}
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/locale-false'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/locale-false?nextLocale=fr'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ nextLocale: 'fr' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe(
'en-US'
)
await browser.elementByCss('#to-another').click()
await browser.waitForElementByCss('#another')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/another'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/another'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('fr')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({})
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('fr')
let parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe(`${ctx.basePath}/fr/another`)
expect(parsedUrl.query).toEqual({})
await browser.eval('window.history.back()')
await browser.waitForElementByCss('#links')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/locale-false'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/locale-false?nextLocale=fr'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ nextLocale: 'fr' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe(
'en-US'
)
parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe(`${ctx.basePath}/locale-false`)
expect(parsedUrl.query).toEqual({ nextLocale: 'fr' })
await browser.eval('window.history.forward()')
await browser.waitForElementByCss('#another')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/another'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/another'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('fr')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({})
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('fr')
parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe(`${ctx.basePath}/fr/another`)
expect(parsedUrl.query).toEqual({})
expect(await browser.eval('window.beforeNav')).toBe(1)
expect(await browser.eval('window.caughtWarns')).toEqual([])
})
it('should navigate with locale false correctly GSP', async () => {
const browser = await webdriver(
ctx.appPort,
`${ctx.basePath}/locale-false?nextLocale=nl`
)
await addDefaultLocaleCookie(browser)
await browser.eval('window.beforeNav = 1')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/locale-false'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/locale-false?nextLocale=nl'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ nextLocale: 'nl' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe(
'en-US'
)
await browser.elementByCss('#to-fallback-first').click()
await browser.waitForElementByCss('#gsp')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/gsp/fallback/[slug]'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/gsp/fallback/first'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('nl')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ slug: 'first' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('nl')
let parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe(`${ctx.basePath}/nl/gsp/fallback/first`)
expect(parsedUrl.query).toEqual({})
await browser.eval('window.history.back()')
await browser.waitForElementByCss('#links')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/locale-false'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/locale-false?nextLocale=nl'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ nextLocale: 'nl' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe(
'en-US'
)
parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe(`${ctx.basePath}/locale-false`)
expect(parsedUrl.query).toEqual({ nextLocale: 'nl' })
await browser.eval('window.history.forward()')
await browser.waitForElementByCss('#gsp')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/gsp/fallback/[slug]'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/gsp/fallback/first'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('nl')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({ slug: 'first' })
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('nl')
parsedUrl = url.parse(await browser.eval('window.location.href'), true)
expect(parsedUrl.pathname).toBe(`${ctx.basePath}/nl/gsp/fallback/first`)
expect(parsedUrl.query).toEqual({})
expect(await browser.eval('window.beforeNav')).toBe(1)
expect(await browser.eval('window.caughtWarns')).toEqual([])
})
it('should update asPath on the client correctly', async () => {
for (const check of ['en', 'En']) {
const browser = await webdriver(ctx.appPort, `${ctx.basePath}/${check}`)
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('en')
expect(await browser.elementByCss('#router-locale').text()).toBe('en')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(await browser.elementByCss('#router-as-path').text()).toBe('/')
expect(await browser.elementByCss('#router-pathname').text()).toBe('/')
}
})
if (!ctx.isDev) {
it('should handle fallback correctly after generating', async () => {
const browser = await webdriver(
ctx.appPort,
`${ctx.basePath}/en/gsp/fallback/hello-fallback`
)
// wait for the fallback to be generated/stored to ISR cache
browser.waitForElementByCss('#gsp')
// now make sure we're serving the previously generated file from the cache
const html = await renderViaHTTP(
ctx.appPort,
`${ctx.basePath}/en/gsp/fallback/hello-fallback`
)
const $ = cheerio.load(html)
expect($('#gsp').text()).toBe('gsp page')
expect($('#router-locale').text()).toBe('en')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect($('#router-pathname').text()).toBe('/gsp/fallback/[slug]')
expect($('#router-as-path').text()).toBe('/gsp/fallback/hello-fallback')
})
}
it('should use correct default locale for locale domains', async () => {
const res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath || '/'}`,
undefined,
{
headers: {
host: 'example.fr',
},
}
)
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect($('html').attr('lang')).toBe('fr')
expect($('#router-locale').text()).toBe('fr')
expect($('#router-as-path').text()).toBe('/')
expect($('#router-pathname').text()).toBe('/')
// expect(JSON.parse($('#router-locales').text())).toEqual(['fr','fr-BE'])
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
const res2 = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath || '/'}`,
undefined,
{
headers: {
host: 'example.be',
},
}
)
expect(res2.status).toBe(200)
const html2 = await res2.text()
const $2 = cheerio.load(html2)
expect($2('html').attr('lang')).toBe('nl-BE')
expect($2('#router-locale').text()).toBe('nl-BE')
expect($2('#router-as-path').text()).toBe('/')
expect($2('#router-pathname').text()).toBe('/')
// expect(JSON.parse($2('#router-locales').text())).toEqual(['nl-BE','fr-BE'])
expect(JSON.parse($2('#router-locales').text())).toEqual(locales)
})
it('should not strip locale prefix for default locale with locale domains', async () => {
const res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath}/fr`,
undefined,
{
headers: {
host: 'example.fr',
},
redirect: 'manual',
}
)
expect(res.status).toBe(200)
// const result = url.parse(res.headers.get('location'), true)
// expect(result.pathname).toBe('/')
// expect(result.query).toEqual({})
const res2 = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath}/nl-BE`,
undefined,
{
headers: {
host: 'example.be',
},
redirect: 'manual',
}
)
expect(res2.status).toBe(200)
// const result2 = url.parse(res2.headers.get('location'), true)
// expect(result2.pathname).toBe('/')
// expect(result2.query).toEqual({})
})
// ('should set locale cookie when removing default locale and accept-lang doesnt match', async () => {
// const res = await fetchViaHTTP(ctx.appPort, '/en-US', undefined, {
// headers: {
// 'accept-language': 'nl',
// },
// redirect: 'manual',
// })
// expect(res.status).toBe(307)
// const parsedUrl = url.parse(res.headers.get('location'), true)
// expect(parsedUrl.pathname).toBe('/')
// expect(parsedUrl.query).toEqual({})
// expect(res.headers.get('set-cookie')).toContain('NEXT_LOCALE=en-US')
// })
it('should not redirect to accept-lang preferred locale with locale cookie', async () => {
const res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath || '/'}`,
undefined,
{
headers: {
'accept-language': 'nl',
cookie: 'NEXT_LOCALE=en-US',
},
redirect: 'manual',
}
)
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect($('#router-locale').text()).toBe('en-US')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect($('html').attr('lang')).toBe('en-US')
expect($('#router-pathname').text()).toBe('/')
expect($('#router-as-path').text()).toBe('/')
})
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, locale, location] = check
const res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath || '/'}`,
undefined,
{
headers: {
host: domain,
'accept-language': locale,
},
redirect: 'manual',
}
)
expect(res.status).toBe(307)
expect(res.headers.get('location')).toBe(location)
}
})
it('should handle locales with domain', async () => {
const domainItems = [
{
// 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'],
},
]
const domainLocales = domainItems.reduce((prev, cur) => {
return [...prev, ...cur.locales]
}, [])
const checkDomainLocales = async (
domainDefault = '',
domain = '',
locale = ''
) => {
const res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath || '/'}`,
undefined,
{
headers: {
host: domain,
'accept-language': locale,
},
redirect: 'manual',
}
)
const expectedDomainItem = domainItems.find(
(item) => item.defaultLocale === locale || item.locales.includes(locale)
)
const shouldRedirect =
expectedDomainItem.domain !== domain ||
locale !== expectedDomainItem.defaultLocale
expect(res.status).toBe(shouldRedirect ? 307 : 200)
if (shouldRedirect) {
const parsedUrl = url.parse(res.headers.get('location'), true)
expect(parsedUrl.pathname).toBe(
`/${expectedDomainItem.defaultLocale === locale ? '' : locale}`
)
expect(parsedUrl.query).toEqual({})
expect(parsedUrl.hostname).toBe(expectedDomainItem.domain)
} else {
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(locales)
// this will not be the domain's defaultLocale since we don't
// generate a prerendered version for each locale domain currently
expect($('#router-default-locale').text()).toBe('en-US')
}
}
for (const item of domainItems) {
for (const locale of domainLocales) {
await checkDomainLocales(item.defaultLocale, item.domain, locale)
}
}
})
it('should provide correctly defaultLocale for locale domain', async () => {
for (const { host, locale } of [
{ host: 'example.fr', locale: 'fr' },
{ host: 'example.be', locale: 'nl-BE' },
]) {
const res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath}/gssp`,
undefined,
{
redirect: 'manual',
headers: {
host,
},
}
)
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect($('#router-locale').text()).toBe(locale)
expect($('#router-default-locale').text()).toBe(locale)
expect(JSON.parse($('#props').text())).toEqual({
defaultLocale: locale,
locale,
locales,
})
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
}
})
it('should generate AMP pages with all locales', async () => {
for (const locale of locales) {
const localePath = locale !== 'en-US' ? `/${locale}` : ''
const html = await renderViaHTTP(
ctx.appPort,
`${ctx.basePath}${localePath}/amp/amp-hybrid`
)
const $ = cheerio.load(html)
expect($('html').attr('lang')).toBe(locale)
expect($('#is-amp').text()).toBe('no')
expect($('#router-locale').text()).toBe(locale)
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect($('#router-pathname').text()).toBe('/amp/amp-hybrid')
expect($('#router-as-path').text()).toBe('/amp/amp-hybrid')
expect(JSON.parse($('#router-query').text())).toEqual({})
const amphtmlPath = `${ctx.basePath}${localePath}/amp/amp-hybrid${
ctx.isDev ? '?amp=1' : '.amp'
}`
expect($('link[rel=amphtml]').attr('href')).toBe(amphtmlPath)
const html2 = await renderViaHTTP(ctx.appPort, amphtmlPath)
const $2 = cheerio.load(html2)
expect($2('html').attr('lang')).toBe(locale)
expect($2('#is-amp').text()).toBe('yes')
expect($2('#router-locale').text()).toBe(locale)
expect(JSON.parse($2('#router-locales').text())).toEqual(locales)
expect($2('#router-pathname').text()).toBe('/amp/amp-hybrid')
expect($2('#router-as-path').text()).toBe('/amp/amp-hybrid')
expect(JSON.parse($2('#router-query').text())).toEqual({ amp: '1' })
expect($2('link[rel=amphtml]').attr('href')).toBeFalsy()
}
})
it('should work with AMP first page with all locales', async () => {
for (const locale of locales) {
const localePath = locale !== 'en-US' ? `/${locale}` : ''
const html = await renderViaHTTP(
ctx.appPort,
`${ctx.basePath}${localePath}/amp/amp-first`
)
const $ = cheerio.load(html)
expect($('html').attr('lang')).toBe(locale)
expect($('#is-amp').text()).toBe('yes')
expect($('#router-locale').text()).toBe(locale)
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect($('#router-pathname').text()).toBe('/amp/amp-first')
expect($('#router-as-path').text()).toBe('/amp/amp-first')
expect(JSON.parse($('#router-query').text())).toEqual({})
expect($('link[rel=amphtml]').attr('href')).toBeFalsy()
}
})
it('should generate fallbacks with all locales', async () => {
for (const locale of locales) {
const html = await renderViaHTTP(
ctx.appPort,
`${ctx.basePath}/${locale}/gsp/fallback/${Math.random()}`
)
const $ = cheerio.load(html)
expect($('html').attr('lang')).toBe(locale)
}
})
it('should generate auto-export page with all locales', async () => {
for (const locale of locales) {
const html = await renderViaHTTP(ctx.appPort, `${ctx.basePath}/${locale}`)
const $ = cheerio.load(html)
expect($('html').attr('lang')).toBe(locale)
expect($('#router-locale').text()).toBe(locale)
expect($('#router-as-path').text()).toBe('/')
expect($('#router-pathname').text()).toBe('/')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
const html2 = await renderViaHTTP(
ctx.appPort,
`${ctx.basePath}/${locale}/auto-export`
)
const $2 = cheerio.load(html2)
expect($2('html').attr('lang')).toBe(locale)
expect($2('#router-locale').text()).toBe(locale)
expect($2('#router-as-path').text()).toBe('/auto-export')
expect($2('#router-pathname').text()).toBe('/auto-export')
expect(JSON.parse($2('#router-locales').text())).toEqual(locales)
}
})
it('should generate non-dynamic GSP page with all locales', async () => {
for (const locale of locales) {
const html = await renderViaHTTP(
ctx.appPort,
`${ctx.basePath}/${locale}/gsp`
)
const $ = cheerio.load(html)
expect($('html').attr('lang')).toBe(locale)
expect($('#router-locale').text()).toBe(locale)
expect($('#router-as-path').text()).toBe('/gsp')
expect($('#router-pathname').text()).toBe('/gsp')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
// make sure locale is case-insensitive
const html2 = await renderViaHTTP(
ctx.appPort,
`${ctx.basePath}/${locale.toUpperCase()}/gsp`
)
const $2 = cheerio.load(html2)
expect($2('html').attr('lang')).toBe(locale)
expect($2('#router-locale').text()).toBe(locale)
expect($2('#router-as-path').text()).toBe('/gsp')
expect($2('#router-pathname').text()).toBe('/gsp')
expect(JSON.parse($2('#router-locales').text())).toEqual(locales)
}
})
if (!ctx.isDev) {
it('should not output GSP pages that returned notFound', async () => {
const skippedLocales = ['en', 'nl']
for (const locale of locales) {
const pagePath = join(ctx.buildPagesDir, locale, 'not-found.html')
const dataPath = join(ctx.buildPagesDir, locale, 'not-found.json')
console.log(pagePath)
expect(await fs.exists(pagePath)).toBe(!skippedLocales.includes(locale))
expect(await fs.exists(dataPath)).toBe(!skippedLocales.includes(locale))
}
})
}
it('should 404 for GSP pages that returned notFound', async () => {
const skippedLocales = ['en', 'nl']
for (const locale of locales) {
const res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath}/${locale}/not-found`
)
expect(res.status).toBe(skippedLocales.includes(locale) ? 404 : 200)
if (skippedLocales.includes(locale)) {
const browser = await webdriver(
ctx.appPort,
`${ctx.basePath}/${locale}/not-found`
)
expect(await browser.elementByCss('html').getAttribute('lang')).toBe(
locale
)
expect(
await browser.eval('document.documentElement.innerHTML')
).toContain('This page could not be found')
const props = JSON.parse(await browser.elementByCss('#props').text())
expect(props.is404).toBe(true)
expect(props.locale).toBe(locale)
const parsedUrl = url.parse(
await browser.eval('window.location.href'),
true
)
expect(parsedUrl.pathname).toBe(`${ctx.basePath}/${locale}/not-found`)
expect(parsedUrl.query).toEqual({})
}
}
})
it('should transition on client properly for page that starts with locale', async () => {
const browser = await webdriver(ctx.appPort, `${ctx.basePath}/fr`)
await browser.eval(`(function() {
window.beforeNav = 1
window.next.router.push('/frank')
})()`)
await browser.waitForElementByCss('#frank')
expect(await browser.elementByCss('#router-locale').text()).toBe('fr')
expect(await browser.elementByCss('#router-default-locale').text()).toBe(
'en-US'
)
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({})
expect(await browser.elementByCss('#router-pathname').text()).toBe('/frank')
expect(await browser.elementByCss('#router-as-path').text()).toBe('/frank')
expect(
url.parse(await browser.eval(() => window.location.href)).pathname
).toBe(`${ctx.basePath}/fr/frank`)
expect(await browser.eval('window.beforeNav')).toBe(1)
})
it('should 404 for GSP that returned notFound on client-transition', async () => {
const browser = await webdriver(ctx.appPort, `${ctx.basePath}/en`)
await browser.eval(`(function() {
window.beforeNav = 1
window.next.router.push('/not-found')
})()`)
await browser.waitForElementByCss('h1')
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('en')
expect(await browser.elementByCss('html').text()).toContain(
'This page could not be found'
)
const props = JSON.parse(await browser.elementByCss('#props').text())
expect(props.is404).toBe(true)
expect(props.locale).toBe('en')
expect(await browser.eval('window.beforeNav')).toBe(null)
})
it('should render 404 for fallback page that returned 404 on client transition', async () => {
const browser = await webdriver(
ctx.appPort,
`${ctx.basePath}/en`,
true,
true
)
await browser.eval(`(function() {
next.router.push('/not-found/fallback/first')
})()`)
await browser.waitForElementByCss('h1')
await browser.eval('window.beforeNav = 1')
expect(await browser.elementByCss('html').text()).toContain(
'This page could not be found'
)
const props = JSON.parse(await browser.elementByCss('#props').text())
expect(props.is404).toBe(true)
expect(props.locale).toBe('en')
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('en')
const parsedUrl = url.parse(
await browser.eval('window.location.href'),
true
)
expect(parsedUrl.pathname).toBe(
`${ctx.basePath}/en/not-found/fallback/first`
)
expect(parsedUrl.query).toEqual({})
if (ctx.isDev) {
// make sure page doesn't reload un-necessarily in development
await waitFor(10 * 1000)
}
expect(await browser.eval('window.beforeNav')).toBe(1)
})
it('should render 404 for fallback page that returned 404', async () => {
const browser = await webdriver(
ctx.appPort,
`${ctx.basePath}/en/not-found/fallback/first`,
true,
true
)
await browser.waitForElementByCss('h1')
await browser.eval('window.beforeNav = 1')
expect(await browser.elementByCss('html').text()).toContain(
'This page could not be found'
)
const props = JSON.parse(await browser.elementByCss('#props').text())
expect(props.is404).toBe(true)
expect(props.locale).toBe('en')
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('en')
const parsedUrl = url.parse(
await browser.eval('window.location.href'),
true
)
expect(parsedUrl.pathname).toBe(
`${ctx.basePath}/en/not-found/fallback/first`
)
expect(parsedUrl.query).toEqual({})
if (ctx.isDev) {
// make sure page doesn't reload un-necessarily in development
await waitFor(10 * 1000)
}
expect(await browser.eval('window.beforeNav')).toBe(1)
})
it('should render 404 for blocking fallback page that returned 404 on client transition', async () => {
const browser = await webdriver(
ctx.appPort,
`${ctx.basePath}/en`,
true,
true
)
await browser.eval(`(function() {
next.router.push('/not-found/blocking-fallback/first')
})()`)
await browser.waitForElementByCss('h1')
await browser.eval('window.beforeNav = 1')
expect(await browser.elementByCss('html').text()).toContain(
'This page could not be found'
)
const props = JSON.parse(await browser.elementByCss('#props').text())
expect(props.is404).toBe(true)
expect(props.locale).toBe('en')
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('en')
const parsedUrl = url.parse(
await browser.eval('window.location.href'),
true
)
expect(parsedUrl.pathname).toBe(
`${ctx.basePath}/en/not-found/blocking-fallback/first`
)
expect(parsedUrl.query).toEqual({})
if (ctx.isDev) {
// make sure page doesn't reload un-necessarily in development
await waitFor(10 * 1000)
}
expect(await browser.eval('window.beforeNav')).toBe(1)
})
it('should render 404 for blocking fallback page that returned 404', async () => {
const browser = await webdriver(
ctx.appPort,
`${ctx.basePath}/en/not-found/blocking-fallback/first`,
true,
true
)
await browser.waitForElementByCss('h1')
await browser.eval('window.beforeNav = 1')
expect(await browser.elementByCss('html').text()).toContain(
'This page could not be found'
)
const props = JSON.parse(await browser.elementByCss('#props').text())
expect(props.is404).toBe(true)
expect(props.locale).toBe('en')
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('en')
const parsedUrl = url.parse(
await browser.eval('window.location.href'),
true
)
expect(parsedUrl.pathname).toBe(
`${ctx.basePath}/en/not-found/blocking-fallback/first`
)
expect(parsedUrl.query).toEqual({})
if (ctx.isDev) {
// make sure page doesn't reload un-necessarily in development
await waitFor(10 * 1000)
}
expect(await browser.eval('window.beforeNav')).toBe(1)
})
it('should not remove locale prefix for default locale', async () => {
const res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath}/en-US`,
undefined,
{
redirect: 'manual',
headers: {
'Accept-Language': 'en-US;q=0.9',
},
}
)
expect(res.status).toBe(200)
// const parsedUrl = url.parse(res.headers.get('location'), true)
// expect(parsedUrl.pathname).toBe('/')
// expect(parsedUrl.query).toEqual({})
// make sure locale is case-insensitive
const res2 = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath}/eN-Us`,
undefined,
{
redirect: 'manual',
headers: {
'Accept-Language': 'en-US;q=0.9',
},
}
)
expect(res2.status).toBe(200)
// const parsedUrl2 = url.parse(res.headers.get('location'), true)
// expect(parsedUrl2.pathname).toBe('/')
// expect(parsedUrl2.query).toEqual({})
})
it('should load getStaticProps page correctly SSR (default locale no prefix)', async () => {
const html = await renderViaHTTP(ctx.appPort, `${ctx.basePath}/gsp`)
const $ = cheerio.load(html)
expect(JSON.parse($('#props').text())).toEqual({
locale: 'en-US',
locales,
defaultLocale: 'en-US',
})
expect($('#router-locale').text()).toBe('en-US')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect($('html').attr('lang')).toBe('en-US')
})
it('should load getStaticProps fallback prerender page correctly SSR (default locale no prefix)', async () => {
const html = await renderViaHTTP(
ctx.appPort,
`${ctx.basePath}/gsp/fallback/first`
)
const $ = cheerio.load(html)
expect(JSON.parse($('#props').text())).toEqual({
locale: 'en-US',
locales,
params: {
slug: 'first',
},
defaultLocale: 'en-US',
})
expect(JSON.parse($('#router-query').text())).toEqual({
slug: 'first',
})
expect($('#router-locale').text()).toBe('en-US')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect($('html').attr('lang')).toBe('en-US')
})
it('should load getStaticProps fallback non-prerender page correctly (default locale no prefix', async () => {
const browser = await webdriver(
ctx.appPort,
`${ctx.basePath}/gsp/fallback/another`
)
await browser.waitForElementByCss('#props')
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
locale: 'en-US',
locales,
params: {
slug: 'another',
},
defaultLocale: 'en-US',
})
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({
slug: 'another',
})
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
})
it('should redirect to locale prefixed route for /', async () => {
const res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath || '/'}`,
undefined,
{
redirect: 'manual',
headers: {
'Accept-Language': 'nl-NL,nl;q=0.9,en-US;q=0.8,en;q=0.7',
},
}
)
expect(res.status).toBe(307)
const parsedUrl = url.parse(res.headers.get('location'), true)
expect(parsedUrl.pathname).toBe(`${ctx.basePath}/nl-NL`)
expect(parsedUrl.query).toEqual({})
const res2 = await fetchViaHTTP(
ctx.appPort,
'/',
{ hello: 'world' },
{
redirect: 'manual',
headers: {
'Accept-Language': 'en;q=0.9',
},
}
)
expect(res2.status).toBe(307)
const parsedUrl2 = url.parse(res2.headers.get('location'), true)
expect(parsedUrl2.pathname).toBe(`${ctx.basePath}/en`)
expect(parsedUrl2.query).toEqual({ hello: 'world' })
})
it('should use default locale for / without accept-language', async () => {
const res = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath || '/'}`,
undefined,
{
redirect: 'manual',
}
)
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect($('#router-locale').text()).toBe('en-US')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect(JSON.parse($('#router-query').text())).toEqual({})
expect($('#router-pathname').text()).toBe('/')
expect($('#router-as-path').text()).toBe('/')
const res2 = await fetchViaHTTP(
ctx.appPort,
`${ctx.basePath || '/'}`,
{ hello: 'world' },
{
redirect: 'manual',
}
)
expect(res2.status).toBe(200)
const html2 = await res2.text()
const $2 = cheerio.load(html2)
expect($2('#router-locale').text()).toBe('en-US')
expect(JSON.parse($2('#router-locales').text())).toEqual(locales)
// page is auto-export so query isn't hydrated until client
expect(JSON.parse($2('#router-query').text())).toEqual({})
expect($2('#router-pathname').text()).toBe('/')
// expect($2('#router-as-path').text()).toBe('/')
})
it('should load getStaticProps page correctly SSR', async () => {
const html = await renderViaHTTP(ctx.appPort, `${ctx.basePath}/en-US/gsp`)
const $ = cheerio.load(html)
expect(JSON.parse($('#props').text())).toEqual({
locale: 'en-US',
locales,
defaultLocale: 'en-US',
})
expect($('#router-locale').text()).toBe('en-US')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect($('html').attr('lang')).toBe('en-US')
})
it('should load getStaticProps fallback prerender page correctly SSR', async () => {
const html = await renderViaHTTP(
ctx.appPort,
`${ctx.basePath}/en-US/gsp/fallback/first`
)
const $ = cheerio.load(html)
expect(JSON.parse($('#props').text())).toEqual({
locale: 'en-US',
locales,
params: {
slug: 'first',
},
defaultLocale: 'en-US',
})
expect(JSON.parse($('#router-query').text())).toEqual({
slug: 'first',
})
expect($('#router-locale').text()).toBe('en-US')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect($('html').attr('lang')).toBe('en-US')
})
it('should load getStaticProps fallback non-prerender page correctly', async () => {
const browser = await webdriver(
ctx.appPort,
`${ctx.basePath}/en/gsp/fallback/another`
)
await browser.waitForElementByCss('#props')
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
locale: 'en',
locales,
params: {
slug: 'another',
},
defaultLocale: 'en-US',
})
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({
slug: 'another',
})
expect(await browser.elementByCss('#router-locale').text()).toBe('en')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(await browser.elementByCss('html').getAttribute('lang')).toBe('en')
})
it('should load getServerSideProps page correctly SSR (default locale no prefix)', async () => {
const html = await renderViaHTTP(ctx.appPort, `${ctx.basePath}/gssp`)
const $ = cheerio.load(html)
expect(JSON.parse($('#props').text())).toEqual({
locale: 'en-US',
locales,
defaultLocale: 'en-US',
})
expect($('#router-locale').text()).toBe('en-US')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect(JSON.parse($('#router-query').text())).toEqual({})
expect($('html').attr('lang')).toBe('en-US')
})
it('should navigate client side for default locale with no prefix', async () => {
const browser = await webdriver(ctx.appPort, `${ctx.basePath || '/'}`)
await addDefaultLocaleCookie(browser)
const checkIndexValues = async () => {
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({})
expect(await browser.elementByCss('#router-pathname').text()).toBe('/')
expect(await browser.elementByCss('#router-as-path').text()).toBe('/')
expect(
url.parse(await browser.eval(() => window.location.href)).pathname
).toBe(`${ctx.basePath || '/'}`)
}
await checkIndexValues()
await browser.elementByCss('#to-another').click()
await browser.waitForElementByCss('#another')
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
locale: 'en-US',
locales,
defaultLocale: 'en-US',
})
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({})
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/another'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/another'
)
expect(
url.parse(await browser.eval(() => window.location.href)).pathname
).toBe(`${ctx.basePath}/another`)
await browser.elementByCss('#to-index').click()
await browser.waitForElementByCss('#index')
await checkIndexValues()
await browser.elementByCss('#to-gsp').click()
await browser.waitForElementByCss('#gsp')
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
locale: 'en-US',
locales,
defaultLocale: 'en-US',
})
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({})
expect(await browser.elementByCss('#router-pathname').text()).toBe('/gsp')
expect(await browser.elementByCss('#router-as-path').text()).toBe('/gsp')
expect(
url.parse(await browser.eval(() => window.location.href)).pathname
).toBe(`${ctx.basePath}/gsp`)
await browser.elementByCss('#to-index').click()
await browser.waitForElementByCss('#index')
await checkIndexValues()
await browser.manage().deleteCookie('NEXT_LOCALE')
})
it('should load getStaticProps fallback non-prerender page another locale correctly', async () => {
const browser = await webdriver(
ctx.appPort,
`${ctx.basePath}/nl-NL/gsp/fallback/another`
)
await browser.waitForElementByCss('#props')
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
locale: 'nl-NL',
locales,
params: {
slug: 'another',
},
defaultLocale: 'en-US',
})
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({
slug: 'another',
})
expect(await browser.elementByCss('#router-locale').text()).toBe('nl-NL')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
})
it('should load getStaticProps non-fallback correctly', async () => {
const browser = await webdriver(
ctx.appPort,
`${ctx.basePath}/en-US/gsp/no-fallback/first`
)
await browser.waitForElementByCss('#props')
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
locale: 'en-US',
locales,
params: {
slug: 'first',
},
defaultLocale: 'en-US',
})
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({
slug: 'first',
})
expect(await browser.elementByCss('#router-locale').text()).toBe('en-US')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(await browser.elementByCss('html').getAttribute('lang')).toBe(
'en-US'
)
})
it('should load getStaticProps non-fallback correctly another locale', async () => {
const browser = await webdriver(
ctx.appPort,
`${ctx.basePath}/nl-NL/gsp/no-fallback/second`
)
await browser.waitForElementByCss('#props')
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
locale: 'nl-NL',
locales,
params: {
slug: 'second',
},
defaultLocale: 'en-US',
})
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({
slug: 'second',
})
expect(await browser.elementByCss('#router-locale').text()).toBe('nl-NL')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(await browser.elementByCss('html').getAttribute('lang')).toBe(
'nl-NL'
)
})
it('should load getStaticProps non-fallback correctly another locale via cookie', async () => {
const html = await renderViaHTTP(
ctx.appPort,
`${ctx.basePath}/nl-NL/gsp/no-fallback/second`,
{},
{
headers: {
cookie: 'NEXT_LOCALE=nl-NL',
},
}
)
const $ = cheerio.load(html)
expect(JSON.parse($('#props').text())).toEqual({
locale: 'nl-NL',
locales,
params: {
slug: 'second',
},
defaultLocale: 'en-US',
})
expect(JSON.parse($('#router-query').text())).toEqual({
slug: 'second',
})
expect($('#router-locale').text()).toBe('nl-NL')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect($('html').attr('lang')).toBe('nl-NL')
})
it('should load getServerSideProps page correctly SSR', async () => {
const html = await renderViaHTTP(ctx.appPort, `${ctx.basePath}/en-US/gssp`)
const $ = cheerio.load(html)
expect(JSON.parse($('#props').text())).toEqual({
locale: 'en-US',
locales,
defaultLocale: 'en-US',
})
expect($('#router-locale').text()).toBe('en-US')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect(JSON.parse($('#router-query').text())).toEqual({})
expect($('html').attr('lang')).toBe('en-US')
const html2 = await renderViaHTTP(ctx.appPort, `${ctx.basePath}/nl-NL/gssp`)
const $2 = cheerio.load(html2)
expect(JSON.parse($2('#props').text())).toEqual({
locale: 'nl-NL',
locales,
defaultLocale: 'en-US',
})
expect($2('#router-locale').text()).toBe('nl-NL')
expect(JSON.parse($2('#router-locales').text())).toEqual(locales)
expect(JSON.parse($2('#router-query').text())).toEqual({})
expect($2('html').attr('lang')).toBe('nl-NL')
})
it('should load dynamic getServerSideProps page correctly SSR', async () => {
const html = await renderViaHTTP(
ctx.appPort,
`${ctx.basePath}/en-US/gssp/first`
)
const $ = cheerio.load(html)
expect(JSON.parse($('#props').text())).toEqual({
locale: 'en-US',
locales,
params: {
slug: 'first',
},
defaultLocale: 'en-US',
})
expect($('#router-locale').text()).toBe('en-US')
expect(JSON.parse($('#router-locales').text())).toEqual(locales)
expect(JSON.parse($('#router-query').text())).toEqual({ slug: 'first' })
expect($('html').attr('lang')).toBe('en-US')
const html2 = await renderViaHTTP(
ctx.appPort,
`${ctx.basePath}/nl-NL/gssp/first`
)
const $2 = cheerio.load(html2)
expect(JSON.parse($2('#props').text())).toEqual({
locale: 'nl-NL',
locales,
params: {
slug: 'first',
},
defaultLocale: 'en-US',
})
expect($2('#router-locale').text()).toBe('nl-NL')
expect(JSON.parse($2('#router-locales').text())).toEqual(locales)
expect(JSON.parse($2('#router-query').text())).toEqual({ slug: 'first' })
expect($2('html').attr('lang')).toBe('nl-NL')
})
it('should navigate to another page and back correctly with locale', async () => {
const browser = await webdriver(ctx.appPort, `${ctx.basePath}/en`)
await browser.eval('window.beforeNav = "hi"')
await browser
.elementByCss('#to-another')
.click()
.waitForElementByCss('#another')
expect(await browser.elementByCss('#router-pathname').text()).toBe(
'/another'
)
expect(await browser.elementByCss('#router-as-path').text()).toBe(
'/another'
)
expect(await browser.elementByCss('#router-locale').text()).toBe('en')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
locale: 'en',
locales,
defaultLocale: 'en-US',
})
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({})
expect(await browser.eval('window.beforeNav')).toBe('hi')
await browser.back().waitForElementByCss('#index')
expect(await browser.eval('window.beforeNav')).toBe('hi')
expect(await browser.elementByCss('#router-pathname').text()).toBe('/')
expect(await browser.elementByCss('#router-as-path').text()).toBe('/')
})
it('should navigate to getStaticProps page and back correctly with locale', async () => {
const browser = await webdriver(ctx.appPort, `${ctx.basePath}/en`)
await browser.eval('window.beforeNav = "hi"')
await browser.elementByCss('#to-gsp').click().waitForElementByCss('#gsp')
expect(await browser.elementByCss('#router-pathname').text()).toBe('/gsp')
expect(await browser.elementByCss('#router-as-path').text()).toBe('/gsp')
expect(await browser.elementByCss('#router-locale').text()).toBe('en')
expect(
JSON.parse(await browser.elementByCss('#router-locales').text())
).toEqual(locales)
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
locale: 'en',
locales,
defaultLocale: 'en-US',
})
expect(
JSON.parse(await browser.elementByCss('#router-query').text())
).toEqual({})
expect(await browser.eval('window.beforeNav')).toBe('hi')
await browser.back().waitForElementByCss('#index')
expect(await browser.eval('window.beforeNav')).toBe('hi')
expect(await browser.elementByCss('#router-pathname').text()).toBe('/')
expect(await browser.elementByCss('#router-as-path').text()).toBe('/')
})
}
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