Unverified Commit 45b8c885 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Ensure fallback rewrites dont match over pages with i18n (#23674)

This ensures we are checking the filesystem correctly when i18n is used to prevent fallback rewrites from being applied even when a page is matched. Additional tests have been added to ensure these cases are being handled. 

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added

Fixes: https://github.com/vercel/next.js/issues/23577
parent 55c6b7ab
......@@ -125,9 +125,11 @@ export function addLocale(
export function delLocale(path: string, locale?: string) {
if (process.env.__NEXT_I18N_SUPPORT) {
const pathname = pathNoQueryHash(path)
return locale &&
(path.startsWith('/' + locale + '/') || path === '/' + locale)
? path.substr(locale.length + 1) || '/'
(pathname.startsWith('/' + locale + '/') || pathname === '/' + locale)
? (pathname.length === locale.length + 1 ? '/' : '') +
path.substr(locale.length + 1)
: path
}
return path
......@@ -961,7 +963,7 @@ export default class Router implements BaseRouter {
if (pathname !== '/_error') {
if (process.env.__NEXT_HAS_REWRITES && as.startsWith('/')) {
const rewritesResult = resolveRewrites(
addBasePath(addLocale(delBasePath(as), this.locale)),
addBasePath(addLocale(cleanedAs, this.locale)),
pages,
rewrites,
query,
......
......@@ -1037,19 +1037,26 @@ export default class Server {
}
}
private async getPagePath(pathname: string): Promise<string> {
private async getPagePath(
pathname: string,
locales?: string[]
): Promise<string> {
return getPagePath(
pathname,
this.distDir,
this._isLikeServerless,
this.renderOpts.dev
this.renderOpts.dev,
locales
)
}
protected async hasPage(pathname: string): Promise<boolean> {
let found = false
try {
found = !!(await this.getPagePath(pathname))
found = !!(await this.getPagePath(
pathname,
this.nextConfig.i18n?.locales
))
} catch (_) {}
return found
......
......@@ -8,6 +8,7 @@ import {
} from '../lib/constants'
import { normalizePagePath, denormalizePagePath } from './normalize-page-path'
import { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'
import { normalizeLocalePath } from '../lib/i18n/normalize-locale-path'
export function pageNotFoundError(page: string): Error {
const err: any = new Error(`Cannot find module for page: ${page}`)
......@@ -19,7 +20,8 @@ export function getPagePath(
page: string,
distDir: string,
serverless: boolean,
dev?: boolean
dev?: boolean,
locales?: string[]
): string {
const serverBuildPath = join(
distDir,
......@@ -36,11 +38,22 @@ export function getPagePath(
console.error(err)
throw pageNotFoundError(page)
}
let pagePath = pagesManifest[page]
if (!pagesManifest[page]) {
if (!pagesManifest[page] && locales) {
const manifestNoLocales: typeof pagesManifest = {}
for (const key of Object.keys(pagesManifest)) {
manifestNoLocales[normalizeLocalePath(key, locales).pathname] =
pagesManifest[key]
}
pagePath = manifestNoLocales[page]
}
if (!pagePath) {
throw pageNotFoundError(page)
}
return join(serverBuildPath, pagesManifest[page])
return join(serverBuildPath, pagePath)
}
export function requirePage(
......
module.exports = {
i18n: {
locales: ['en', 'fr'],
defaultLocale: 'en',
},
rewrites() {
return {
fallback: [
{
source: '/:path*',
destination: '/another',
},
],
}
},
}
import { useRouter } from 'next/router'
export default function Another(props) {
const router = useRouter()
return (
<p id="router">
{JSON.stringify({
pathname: router.pathname,
asPath: router.asPath,
query: router.query,
another: true,
})}
</p>
)
}
import { useRouter } from 'next/router'
export default function Dynamic(props) {
const router = useRouter()
return (
<p id="router">
{JSON.stringify({
pathname: router.pathname,
asPath: router.asPath,
query: router.query,
dynamic: true,
})}
</p>
)
}
import { useRouter } from 'next/router'
export default function Index(props) {
const router = useRouter()
return (
<p id="router">
{JSON.stringify({
pathname: router.pathname,
asPath: router.asPath,
query: router.query,
index: true,
})}
</p>
)
}
import url from 'url'
import fs from 'fs-extra'
import { join } from 'path'
import webdriver from 'next-webdriver'
import {
nextBuild,
nextStart,
findPort,
killApp,
File,
launchApp,
waitFor,
} from 'next-test-utils'
jest.setTimeout(1000 * 60 * 1)
const appDir = join(__dirname, '../')
const nextConfig = new File(join(appDir, 'next.config.js'))
let appPort
let app
function runTests() {
it('should not rewrite for index page', async () => {
for (const [pathname, query] of [
['/', {}],
['/en', {}],
['/fr', {}],
['/', { hello: 'world' }],
['/en', { hello: 'world' }],
['/fr', { hello: 'world' }],
]) {
const asPath = url.format({ pathname, query })
const browser = await webdriver(appPort, asPath)
expect(JSON.parse(await browser.elementByCss('#router').text())).toEqual({
index: true,
pathname: '/',
asPath: url.format({ pathname: '/', query }),
query,
})
await waitFor(1000)
expect(JSON.parse(await browser.elementByCss('#router').text())).toEqual({
index: true,
pathname: '/',
asPath: url.format({ pathname: '/', query }),
query,
})
}
})
it('should not rewrite for dynamic page', async () => {
for (const [pathname, query] of [
['/dynamic/first', {}],
['/en/dynamic/first', {}],
['/fr/dynamic/first', {}],
['/dynamic/first', { hello: 'world' }],
['/en/dynamic/first', { hello: 'world' }],
['/fr/dynamic/first', { hello: 'world' }],
]) {
const asPath = url.format({ pathname, query })
const browser = await webdriver(appPort, asPath)
expect(JSON.parse(await browser.elementByCss('#router').text())).toEqual({
dynamic: true,
pathname: '/dynamic/[slug]',
asPath: url.format({ pathname: '/dynamic/first', query }),
query: {
...query,
slug: 'first',
},
})
await waitFor(1000)
expect(JSON.parse(await browser.elementByCss('#router').text())).toEqual({
dynamic: true,
pathname: '/dynamic/[slug]',
asPath: url.format({ pathname: '/dynamic/first', query }),
query: {
...query,
slug: 'first',
},
})
}
})
}
describe('i18n Support', () => {
describe('dev mode', () => {
beforeAll(async () => {
await fs.remove(join(appDir, '.next'))
appPort = await findPort()
app = await launchApp(appDir, appPort)
})
afterAll(async () => {
await killApp(app)
nextConfig.restore()
})
runTests()
})
describe('production mode', () => {
beforeAll(async () => {
await fs.remove(join(appDir, '.next'))
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(async () => {
await killApp(app)
nextConfig.restore()
})
runTests()
})
})
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