Unverified Commit 7d77a19a authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Fix fallback: false triggering 404 before rewrites (#24121)

This fixes dynamic pages with `fallback: false` that don't have a matching path causing a 404 before rewrites are checked unexpectedly. This ensures we treat `fallback: false` pages as a match only if they also have a matching static path so that fallback rewrites can be triggered correctly. An additional test suite as been added to ensure this is working as expected. 

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
parent 4b8e5396
...@@ -997,8 +997,11 @@ export default class Server { ...@@ -997,8 +997,11 @@ export default class Server {
parsedUrl.query.__nextLocale = localePathResult.detectedLocale parsedUrl.query.__nextLocale = localePathResult.detectedLocale
} }
} }
const bubbleNoFallback = !!query._nextBubbleNoFallback
if (pathname === '/api' || pathname.startsWith('/api/')) { if (pathname === '/api' || pathname.startsWith('/api/')) {
delete query._nextBubbleNoFallback
const handled = await this.handleApiRequest( const handled = await this.handleApiRequest(
req as NextApiRequest, req as NextApiRequest,
res as NextApiResponse, res as NextApiResponse,
...@@ -1010,10 +1013,20 @@ export default class Server { ...@@ -1010,10 +1013,20 @@ export default class Server {
} }
} }
try {
await this.render(req, res, pathname, query, parsedUrl) await this.render(req, res, pathname, query, parsedUrl)
return { return {
finished: true, finished: true,
} }
} catch (err) {
if (err instanceof NoFallbackError && bubbleNoFallback) {
return {
finished: false,
}
}
throw err
}
}, },
} }
...@@ -1861,6 +1874,9 @@ export default class Server { ...@@ -1861,6 +1874,9 @@ export default class Server {
pathname: string, pathname: string,
query: ParsedUrlQuery = {} query: ParsedUrlQuery = {}
): Promise<string | null> { ): Promise<string | null> {
const bubbleNoFallback = !!query._nextBubbleNoFallback
delete query._nextBubbleNoFallback
try { try {
const result = await this.findPageComponents(pathname, query) const result = await this.findPageComponents(pathname, query)
if (result) { if (result) {
...@@ -1873,7 +1889,9 @@ export default class Server { ...@@ -1873,7 +1889,9 @@ export default class Server {
{ ...this.renderOpts } { ...this.renderOpts }
) )
} catch (err) { } catch (err) {
if (!(err instanceof NoFallbackError)) { const isNoFallbackError = err instanceof NoFallbackError
if (!isNoFallbackError || (isNoFallbackError && bubbleNoFallback)) {
throw err throw err
} }
} }
...@@ -1901,7 +1919,12 @@ export default class Server { ...@@ -1901,7 +1919,12 @@ export default class Server {
{ ...this.renderOpts, params } { ...this.renderOpts, params }
) )
} catch (err) { } catch (err) {
if (!(err instanceof NoFallbackError)) { const isNoFallbackError = err instanceof NoFallbackError
if (
!isNoFallbackError ||
(isNoFallbackError && bubbleNoFallback)
) {
throw err throw err
} }
} }
...@@ -1909,6 +1932,11 @@ export default class Server { ...@@ -1909,6 +1932,11 @@ export default class Server {
} }
} }
} catch (err) { } catch (err) {
const isNoFallbackError = err instanceof NoFallbackError
if (isNoFallbackError && bubbleNoFallback) {
throw err
}
if (err && err.code === 'DECODE_FAILED') { if (err && err.code === 'DECODE_FAILED') {
this.logError(err) this.logError(err)
res.statusCode = 400 res.statusCode = 400
......
...@@ -171,17 +171,17 @@ export default class Router { ...@@ -171,17 +171,17 @@ export default class Router {
// Matched a page or dynamic route so render it using catchAllRoute // Matched a page or dynamic route so render it using catchAllRoute
if (matchedPage) { if (matchedPage) {
checkParsedUrl.pathname = fsPathname
const pageParams = this.catchAllRoute.match(checkParsedUrl.pathname) const pageParams = this.catchAllRoute.match(checkParsedUrl.pathname)
checkParsedUrl.pathname = fsPathname
checkParsedUrl.query._nextBubbleNoFallback = '1'
await this.catchAllRoute.fn( const result = await this.catchAllRoute.fn(
req, req,
res, res,
pageParams as Params, pageParams as Params,
checkParsedUrl checkParsedUrl
) )
return true return result.finished
} }
} }
......
module.exports = {
rewrites() {
return {
fallback: [
{
source: '/:path*',
destination: '/another',
},
],
}
},
}
import { useRouter } from 'next/router'
export const getStaticProps = () => {
return {
props: {
world: 'world',
},
}
}
export const getStaticPaths = () => {
return {
paths: ['/first', '/second'],
fallback: false,
}
}
export default function Page({ world }) {
const router = useRouter()
if (router.isFallback) {
throw new Error('should not have fallback')
}
return (
<>
<p id="slug">hello {world}</p>
<p id="query">{JSON.stringify(router.query)}</p>
</>
)
}
import { useRouter } from 'next/router'
export const getServerSideProps = () => {
return {
props: {},
}
}
export default function Page() {
return (
<>
<p id="another">another</p>
<p id="query">{JSON.stringify(useRouter().query)}</p>
</>
)
}
/* eslint-env jest */
import fs from 'fs-extra'
import { join } from 'path'
import cheerio from 'cheerio'
import webdriver from 'next-webdriver'
import {
killApp,
findPort,
nextBuild,
nextStart,
launchApp,
fetchViaHTTP,
} from 'next-test-utils'
jest.setTimeout(1000 * 60 * 2)
const appDir = join(__dirname, '../')
let appPort
let app
const runTests = () => {
it('should rewrite correctly for path at same level as fallback: false SSR', async () => {
const res = await fetchViaHTTP(appPort, '/hello', undefined, {
redirect: 'manual',
})
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect($('#another').text()).toBe('another')
expect(JSON.parse($('#query').text())).toEqual({
path: ['hello'],
})
})
it('should rewrite correctly for path above fallback: false SSR', async () => {
const res = await fetchViaHTTP(appPort, '/hello/world', undefined, {
redirect: 'manual',
})
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect($('#another').text()).toBe('another')
expect(JSON.parse($('#query').text())).toEqual({
path: ['hello', 'world'],
})
})
it('should rewrite correctly for path at same level as fallback: false client', async () => {
const browser = await webdriver(appPort, '/hello')
expect(await browser.elementByCss('#another').text()).toBe('another')
expect(JSON.parse(await browser.elementByCss('#query').text())).toEqual({
path: ['hello'],
})
})
it('should rewrite correctly for path above fallback: false client', async () => {
const browser = await webdriver(appPort, '/hello/world')
expect(await browser.elementByCss('#another').text()).toBe('another')
expect(JSON.parse(await browser.elementByCss('#query').text())).toEqual({
path: ['hello', 'world'],
})
})
it('should not rewrite for path from fallback: false SSR', async () => {
const res = await fetchViaHTTP(appPort, '/first', undefined, {
redirect: 'manual',
})
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect($('#slug').text()).toContain('hello')
expect(JSON.parse($('#query').text())).toEqual({
slug: 'first',
})
})
it('should not rewrite for path from fallback: false client', async () => {
const browser = await webdriver(appPort, '/second')
expect(await browser.elementByCss('#slug').text()).toContain('hello')
expect(JSON.parse(await browser.elementByCss('#query').text())).toEqual({
slug: 'second',
})
})
}
describe('fallback: false rewrite', () => {
describe('dev mode', () => {
beforeAll(async () => {
await fs.remove(join(appDir, '.next'))
appPort = await findPort()
app = await launchApp(appDir, appPort)
})
afterAll(() => killApp(app))
runTests()
})
describe('production mode', () => {
beforeAll(async () => {
await fs.remove(join(appDir, '.next'))
await nextBuild(appDir, [])
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
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