Commit ed3bfb58 authored by Jimmy Lai's avatar Jimmy Lai

Fix export fallback not-found recovery

parent 174a25ee
...@@ -29,9 +29,10 @@ import { createInitialRSCPayloadFromFallbackPrerender } from './flight-data-help ...@@ -29,9 +29,10 @@ import { createInitialRSCPayloadFromFallbackPrerender } from './flight-data-help
import { getDeploymentId } from '../shared/lib/deployment-id' import { getDeploymentId } from '../shared/lib/deployment-id'
import { setNavigationBuildId } from './navigation-build-id' import { setNavigationBuildId } from './navigation-build-id'
import { import {
addOutputExportDataSuffix, getConfiguredOutputExportNotFoundCandidate,
fetchOutputExportFallbackResponse, fetchOutputExportFallbackResponse,
fetchOutputExportNotFoundDataResponse, fetchOutputExportNotFoundDataResponse,
fetchOutputExportNotFoundResponse,
} from './output-export-fallback' } from './output-export-fallback'
/// <reference types="react-dom/experimental" /> /// <reference types="react-dom/experimental" />
...@@ -306,12 +307,11 @@ if (instantTestStaticFetch) { ...@@ -306,12 +307,11 @@ if (instantTestStaticFetch) {
(await fetchOutputExportNotFoundDataResponse(renderedUrl, { (await fetchOutputExportNotFoundDataResponse(renderedUrl, {
credentials: 'same-origin', credentials: 'same-origin',
})) ?? })) ??
(await fetch( (await fetchOutputExportNotFoundResponse(renderedUrl, {
addOutputExportDataSuffix(new URL('/_not-found', renderedUrl)), credentials: 'same-origin',
{ }))
credentials: 'same-origin', initialOutputExportFallbackBasePath =
} getConfiguredOutputExportNotFoundCandidate(renderedUrl.pathname)
))
return decodeFallbackPrerenderPayload( return decodeFallbackPrerenderPayload(
Promise.resolve(response), Promise.resolve(response),
......
...@@ -4,6 +4,7 @@ import { ...@@ -4,6 +4,7 @@ import {
fetchOutputExportDataResponse, fetchOutputExportDataResponse,
fetchOutputExportFallbackResponse, fetchOutputExportFallbackResponse,
fetchOutputExportNotFoundDataResponse, fetchOutputExportNotFoundDataResponse,
fetchOutputExportNotFoundResponse,
getCachedOutputExportFallbackDataUrl, getCachedOutputExportFallbackDataUrl,
getCachedOutputExportFallbackRequestUrl, getCachedOutputExportFallbackRequestUrl,
getOutputExportFallbackCandidates, getOutputExportFallbackCandidates,
...@@ -13,10 +14,12 @@ import { ...@@ -13,10 +14,12 @@ import {
describe('output export fallback helpers', () => { describe('output export fallback helpers', () => {
const originalFetch = global.fetch const originalFetch = global.fetch
const originalBasePath = process.env.__NEXT_ROUTER_BASEPATH
const originalTrailingSlash = process.env.__NEXT_TRAILING_SLASH const originalTrailingSlash = process.env.__NEXT_TRAILING_SLASH
afterEach(() => { afterEach(() => {
global.fetch = originalFetch global.fetch = originalFetch
process.env.__NEXT_ROUTER_BASEPATH = originalBasePath
process.env.__NEXT_TRAILING_SLASH = originalTrailingSlash process.env.__NEXT_TRAILING_SLASH = originalTrailingSlash
clearOutputExportFallbackManifestCache() clearOutputExportFallbackManifestCache()
jest.restoreAllMocks() jest.restoreAllMocks()
...@@ -410,6 +413,11 @@ describe('output export fallback helpers', () => { ...@@ -410,6 +413,11 @@ describe('output export fallback helpers', () => {
) )
expect(response).not.toBeNull() expect(response).not.toBeNull()
expect(
getCachedOutputExportFallbackDataUrl(
new URL('https://example.com/docs/missing/route.txt')
)?.href
).toBe('https://example.com/docs/_not-found.txt')
expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([ expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([
'https://example.com/docs/missing/route/_not-found.txt', 'https://example.com/docs/missing/route/_not-found.txt',
'https://example.com/docs/missing/route/_not-found/index.txt', 'https://example.com/docs/missing/route/_not-found/index.txt',
...@@ -418,4 +426,32 @@ describe('output export fallback helpers', () => { ...@@ -418,4 +426,32 @@ describe('output export fallback helpers', () => {
'https://example.com/docs/_not-found.txt', 'https://example.com/docs/_not-found.txt',
]) ])
}) })
it('uses the configured app-root not-found artifact as the raw fallback', async () => {
process.env.__NEXT_ROUTER_BASEPATH = '/docs'
process.env.__NEXT_TRAILING_SLASH = 'true'
const fetchMock = jest.fn(async () => {
return new Response('payload', {
status: 200,
headers: { 'content-type': 'application/octet-stream' },
})
})
global.fetch = fetchMock as typeof fetch
const response = await fetchOutputExportNotFoundResponse(
new URL('https://example.com/docs/missing/route/')
)
expect(response.ok).toBe(true)
expect(
getCachedOutputExportFallbackDataUrl(
new URL('https://example.com/docs/missing/route/index.txt')
)?.href
).toBe('https://example.com/docs/_not-found/index.txt')
expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([
'https://example.com/docs/_not-found/index.txt',
])
})
}) })
...@@ -3,9 +3,11 @@ import { ...@@ -3,9 +3,11 @@ import {
getOutputExportFallbackPath, getOutputExportFallbackPath,
type OutputExportFallbackManifestEntry, type OutputExportFallbackManifestEntry,
} from '../lib/output-export-dynamic-fallback' } from '../lib/output-export-dynamic-fallback'
import { addPathPrefix } from '../shared/lib/router/utils/add-path-prefix'
import { RSC_CONTENT_TYPE_HEADER } from './components/app-router-headers' import { RSC_CONTENT_TYPE_HEADER } from './components/app-router-headers'
import { getRouteMatcher } from '../shared/lib/router/utils/route-matcher' import { getRouteMatcher } from '../shared/lib/router/utils/route-matcher'
import { getRouteRegex } from '../shared/lib/router/utils/route-regex' import { getRouteRegex } from '../shared/lib/router/utils/route-regex'
import { normalizePathTrailingSlash } from './normalize-trailing-slash'
type OutputExportFallbackManifest = { type OutputExportFallbackManifest = {
version: 1 version: 1
...@@ -77,6 +79,23 @@ export function getOutputExportNotFoundCandidates(pathname: string): string[] { ...@@ -77,6 +79,23 @@ export function getOutputExportNotFoundCandidates(pathname: string): string[] {
) )
} }
export function getConfiguredOutputExportNotFoundCandidate(
pathname: string
): string {
const configuredPath = normalizeOutputExportRouteDirectory(
normalizePathTrailingSlash(
addPathPrefix('/_not-found', process.env.__NEXT_ROUTER_BASEPATH || '')
)
)
return (
getOutputExportNotFoundCandidates(pathname).find(
(candidate) =>
normalizeOutputExportRouteDirectory(candidate) === configuredPath
) ?? getOutputExportNotFoundPath('')
)
}
export function addOutputExportDataSuffix(url: URL): URL { export function addOutputExportDataSuffix(url: URL): URL {
const nextUrl = new URL(url) const nextUrl = new URL(url)
if (nextUrl.pathname.endsWith('/')) { if (nextUrl.pathname.endsWith('/')) {
...@@ -348,15 +367,41 @@ export async function fetchOutputExportNotFoundDataResponse( ...@@ -348,15 +367,41 @@ export async function fetchOutputExportNotFoundDataResponse(
const candidateUrl = new URL(renderedUrl) const candidateUrl = new URL(renderedUrl)
candidateUrl.pathname = candidate candidateUrl.pathname = candidate
const response = await fetchOutputExportDataResponse(candidateUrl, init) const result = await fetchOutputExportDataResult(candidateUrl, init)
if (response !== null) { if (result !== null) {
return response cacheOutputExportFallbackDataUrl(
renderedUrl,
candidateUrl,
result.dataUrl
)
return result.response
} }
} }
return null return null
} }
export async function fetchOutputExportNotFoundResponse(
renderedUrl: URL,
init?: RequestInit
): Promise<Response> {
// The raw fallback should preserve the configured app root (for example a
// basePath) without probing deeper missing prefixes that may be served by an
// HTML fallback document instead of the RSC not-found payload.
const candidateUrl = new URL(renderedUrl)
candidateUrl.pathname = getConfiguredOutputExportNotFoundCandidate(
renderedUrl.pathname
)
const configuredDataUrl = getConfiguredOutputExportDataUrl(
candidateUrl,
renderedUrl.pathname.endsWith('/')
)
cacheOutputExportFallbackDataUrl(renderedUrl, candidateUrl, configuredDataUrl)
return fetch(configuredDataUrl, init)
}
export async function fetchOutputExportFallbackResponse( export async function fetchOutputExportFallbackResponse(
renderedUrl: URL, renderedUrl: URL,
init?: RequestInit init?: RequestInit
......
...@@ -5,6 +5,9 @@ export default function DocsIndex() { ...@@ -5,6 +5,9 @@ export default function DocsIndex() {
<main> <main>
<h1>Docs</h1> <h1>Docs</h1>
<ul> <ul>
<li>
<Link href="/docs/reference/export">docs reference page</Link>
</li>
<li> <li>
<Link href="/docs/guides/export/fallback"> <Link href="/docs/guides/export/fallback">
docs export fallback page docs export fallback page
......
import Link from 'next/link'
import { Suspense } from 'react'
import ReferenceTopicClient from './topic-client'
export default function DocsReferenceTopicPage() {
return (
<main>
<Suspense fallback={<h1>Loading reference...</h1>}>
<ReferenceTopicClient />
</Suspense>
<ul>
<li>
<Link href="/docs">Visit docs index</Link>
</li>
</ul>
</main>
)
}
'use client'
import { useParams } from 'next/navigation'
export default function ReferenceTopicClient() {
const params = useParams()
return <h1>{`reference:${params.topic ?? 'missing'}`}</h1>
}
import { join } from 'path'
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import webdriver from 'next-webdriver'
import { buildAndStartOutputExportServer } from './utils'
const { next, skipped, isNextDev } = nextTestSetup({
files: join(__dirname, '..', 'fixtures', 'dynamic-fallback-cache-components'),
skipDeployment: true,
skipStart: true,
disableAutoSkewProtection: true,
})
if (skipped) {
describe.skip('app dir - output export dynamic routes with Cache Components and basePath', () => {})
} else {
const describeProduction = isNextDev ? describe.skip : describe
describeProduction(
'app dir - output export dynamic routes with Cache Components and basePath',
() => {
let port: number
let stopOrKill: (() => Promise<void>) | undefined
let getRequests: () => string[]
let clearRequests: () => void
beforeAll(async () => {
await next.patchFile('next.config.js', (content) =>
content.replace(
'cacheComponents: true,',
"cacheComponents: true,\n basePath: '/base',"
)
)
;({ port, stopOrKill, getRequests, clearRequests } =
await buildAndStartOutputExportServer(next, {
basePath: '/base',
trailingSlash: true,
useFallbackDocument: true,
}))
})
afterAll(async () => {
await stopOrKill?.()
await next.destroy()
})
it('keeps unmatched fallback not-found fetches under the basePath', async () => {
clearRequests()
const browser = await webdriver(port, '/base/missing/route/')
try {
await retry(async () => {
expect(await browser.elementByCss('h1').text()).toBe(
'My custom not found page'
)
})
const requests = getRequests()
expect(
requests.some((requestPath) =>
requestPath.startsWith('/base/_not-found/index.txt')
)
).toBe(true)
expect(
requests.some((requestPath) =>
requestPath.startsWith('/_not-found.txt')
)
).toBe(false)
} finally {
await browser.close()
}
})
}
)
}
...@@ -249,6 +249,47 @@ if (skipped) { ...@@ -249,6 +249,47 @@ if (skipped) {
} }
}) })
it('prefers deeper static-prefix fallback routes over shallower overlaps', async () => {
clearRequests()
const browser = await webdriver(port, '/docs/reference/export/')
try {
await retry(async () => {
expect(await browser.elementByCss('h1').text()).toBe(
'reference:export'
)
})
const requests = getRequests()
expect(
requests.some((requestPath) =>
requestPath.startsWith('/docs/__fallback')
)
).toBe(false)
expect(
requests.filter((requestPath) =>
requestPath.startsWith('/docs/reference/__fallback/index.txt')
)
).toHaveLength(1)
await browser.elementByCss('a[href="/docs/"]').click()
await retry(async () => {
expect(await browser.elementByCss('h1').text()).toBe('Docs')
})
await browser
.elementByCss('a[href="/docs/reference/export/"]')
.click()
await retry(async () => {
expect(await browser.elementByCss('h1').text()).toBe(
'reference:export'
)
})
} finally {
await browser.close()
}
})
it('renders optional catch-all fallback routes for empty and nested params', async () => { it('renders optional catch-all fallback routes for empty and nested params', async () => {
const browser = await webdriver(port, '/optional/') const browser = await webdriver(port, '/optional/')
......
...@@ -27,9 +27,11 @@ const glob = promisify(globOrig) ...@@ -27,9 +27,11 @@ const glob = promisify(globOrig)
export async function buildAndStartOutputExportServer( export async function buildAndStartOutputExportServer(
next: Pick<NextInstance, 'build' | 'testDir'>, next: Pick<NextInstance, 'build' | 'testDir'>,
{ {
basePath,
trailingSlash, trailingSlash,
useFallbackDocument, useFallbackDocument,
}: { }: {
basePath?: string
trailingSlash: boolean trailingSlash: boolean
useFallbackDocument: boolean useFallbackDocument: boolean
} }
...@@ -64,6 +66,17 @@ export async function buildAndStartOutputExportServer( ...@@ -64,6 +66,17 @@ export async function buildAndStartOutputExportServer(
nextHandler() nextHandler()
}) })
if (basePath) {
app.use((req, _res, nextHandler) => {
if (req.url === basePath) {
req.url = '/'
} else if (req.url?.startsWith(`${basePath}/`)) {
req.url = req.url.slice(basePath.length)
}
nextHandler()
})
}
app.use( app.use(
express.static(outDir, { express.static(outDir, {
extensions: ['html'], extensions: ['html'],
......
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