Unverified Commit 1bccd951 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Render complete HTML documents after MPA Server Actions (#100740)

MPA form submissions to Cache Components pages could return only the
continuation of a prerender. The action executed, but the response
omitted the HTML document and did not render the returned
`useActionState` value.

This change renders a complete document for MPA form submissions while
retaining the RDC supplied by the prerender. This preserves ordinary
`'use cache'` values on deployments where the default handler has no
prerendered entries in memory. The action handler also prepares the
render phase for MPA form submissions that do not revalidate data.
Ordinary not-found responses include the root layout.

The diagnosis and reproduction in #99981 identified the self-hosted
case. This fix also handles postponed state supplied by Vercel before
the action body, without changing how that body is decoded.

The tests cover plain and stateful forms, both postponed-state variants,
submission before hydration, cache reuse, invalidation, blocking routes,
and ordinary and global not-found responses.

Fixes #99756
Closes #99981
parent 6352f416
...@@ -953,6 +953,7 @@ export async function handleAction({ ...@@ -953,6 +953,7 @@ export async function handleAction({
[], [],
workStore, workStore,
requestStore, requestStore,
false,
actionWasForwarded actionWasForwarded
) )
...@@ -1171,6 +1172,7 @@ export async function handleAction({ ...@@ -1171,6 +1172,7 @@ export async function handleAction({
[], [],
workStore, workStore,
requestStore, requestStore,
false,
actionWasForwarded actionWasForwarded
) )
...@@ -1303,6 +1305,7 @@ export async function handleAction({ ...@@ -1303,6 +1305,7 @@ export async function handleAction({
boundActionArguments, boundActionArguments,
workStore, workStore,
requestStore, requestStore,
isFetchAction,
shouldSkipPageRendering shouldSkipPageRendering
).finally(() => { ).finally(() => {
addRevalidationHeader(res, { workStore, requestStore }) addRevalidationHeader(res, { workStore, requestStore })
...@@ -1467,6 +1470,7 @@ async function executeActionAndPrepareForRender< ...@@ -1467,6 +1470,7 @@ async function executeActionAndPrepareForRender<
args: Parameters<TFn>, args: Parameters<TFn>,
workStore: WorkStore, workStore: WorkStore,
requestStore: RequestStore, requestStore: RequestStore,
isFetchAction: boolean,
shouldSkipPageRendering: boolean shouldSkipPageRendering: boolean
): Promise<{ ): Promise<{
actionResult: Awaited<ReturnType<TFn>> actionResult: Awaited<ReturnType<TFn>>
...@@ -1486,11 +1490,13 @@ async function executeActionAndPrepareForRender< ...@@ -1486,11 +1490,13 @@ async function executeActionAndPrepareForRender<
action.apply(null, args) action.apply(null, args)
) )
// If the page was not revalidated, or if this is an action-only request, // Fetch actions can skip rendering when the page was not revalidated. MPA
// we can skip rendering the page. // form submissions still need a complete HTML response with their form
// state.
skipPageRendering ||= skipPageRendering ||=
workStore.pathWasRevalidated === undefined || isFetchAction &&
workStore.pathWasRevalidated === ActionDidNotRevalidate (workStore.pathWasRevalidated === undefined ||
workStore.pathWasRevalidated === ActionDidNotRevalidate)
return { actionResult, skipPageRendering } return { actionResult, skipPageRendering }
} finally { } finally {
......
...@@ -510,11 +510,14 @@ function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree { ...@@ -510,11 +510,14 @@ function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree {
children: [PAGE_SEGMENT_KEY, {}, notFoundTreeComponents, null], children: [PAGE_SEGMENT_KEY, {}, notFoundTreeComponents, null],
}, },
// Always include global-error so that getGlobalErrorStyles can access it. // Always include global-error so that getGlobalErrorStyles can access it.
// When global-not-found is present, use full components. // When global-not-found is present, use full components. Otherwise, keep
// Otherwise, only include global-error module. // the root layout to render a complete HTML document.
hasGlobalNotFound hasGlobalNotFound
? components ? components
: { 'global-error': components['global-error'] }, : {
layout: components.layout,
'global-error': components['global-error'],
},
null, // staticSiblings null, // staticSiblings
] ]
} }
...@@ -2884,6 +2887,13 @@ async function renderAppPage( ...@@ -2884,6 +2887,13 @@ async function renderAppPage(
: stagedFallbackParams : stagedFallbackParams
? new Set(stagedFallbackParams.keys()) ? new Set(stagedFallbackParams.keys())
: null : null
// MPA form submissions need a complete document with the submitted form
// state. Their new render can still reuse the extracted RDC.
if (isPossibleActionRequest && !serverActionRequestMetadata.isFetchAction) {
postponedState = null
}
const createRequestStore = createRequestStoreForRender.bind( const createRequestStore = createRequestStoreForRender.bind(
null, null,
requestHeaders, requestHeaders,
......
'use server'
import { cookies } from 'next/headers'
import { updateTag } from 'next/cache'
import { notFound } from 'next/navigation'
export type FormState = { count: number; message: string }
export async function submitState(
name: string,
previous: FormState,
data: FormData
): Promise<FormState> {
return {
count: previous.count + 1,
message: `${name}:${data.get('message')}`,
}
}
export async function invalidateState(previous: FormState, data: FormData) {
updateTag('mpa-content')
return submitState('invalidate', previous, data)
}
export async function submitPlain(prefix: string, data: FormData) {
const cookieStore = await cookies()
cookieStore.set('mpa-message', `${prefix}:${data.get('message')}`)
}
export async function submitNotFound() {
notFound()
}
import { submitState } from '../actions'
import { StateForm } from '../state-form'
export const instant = false
export default async function Page({ searchParams }: PageProps<'/blocking'>) {
const { query } = await searchParams
return (
<>
<p>Query: {query ?? 'none'}</p>
<StateForm name="blocking" action={submitState.bind(null, 'blocking')} />
</>
)
}
import { connection } from 'next/server'
import { submitState } from '../actions'
import { StateForm } from '../state-form'
async function readRequest() {
await connection()
return 'Request data'
}
// The form does not read its request prop during SSR. HTML can finish while
// Flight still waits for request data.
export default function Page() {
return (
<StateForm
name="data"
action={submitState.bind(null, 'data')}
request={readRequest()}
/>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
import { submitState } from '../actions'
import { StateForm } from '../state-form'
async function DynamicForm() {
await connection()
return <StateForm name="dynamic" action={submitState.bind(null, 'dynamic')} />
}
export default function Page() {
return (
<Suspense fallback={<p>Loading form</p>}>
<DynamicForm />
</Suspense>
)
}
import type { ReactNode } from 'react'
import { readValue } from './read-value'
export default async function Root({ children }: { children: ReactNode }) {
const value = await readValue('layout')
return (
<html>
<body>
<header id="static-shell">MPA action page</header>
<p id="layout-value">{value}</p>
{children}
</body>
</html>
)
}
export default function NotFound() {
return <p id="not-found-message">MPA action not found</p>
}
import { Suspense } from 'react'
import {
submitState,
submitPlain,
submitNotFound,
invalidateState,
} from './actions'
import { StateForm } from './state-form'
import { readValue } from './read-value'
import { RequestContent } from './request-content'
export default async function Page() {
const value = await readValue('content')
return (
<>
<p id="content-value">{value}</p>
<StateForm name="static" action={submitState.bind(null, 'static')} />
<StateForm name="invalidate" action={invalidateState} />
<form action={submitPlain.bind(null, 'bound')}>
<input id="plain-message" name="message" defaultValue="Ada" />
<button id="submit-plain">Submit plain form</button>
</form>
<form action={submitNotFound}>
<button id="submit-not-found">Return not found</button>
</form>
<Suspense fallback={<p>Loading request content</p>}>
<RequestContent />
</Suspense>
</>
)
}
import { randomUUID } from 'crypto'
import { cacheLife, cacheTag } from 'next/cache'
export async function readValue(name: string) {
'use cache'
cacheLife('hours')
cacheTag(`mpa-${name}`)
return `${name}:${randomUUID()}`
}
import { cookies } from 'next/headers'
export async function RequestContent() {
const cookieStore = await cookies()
return (
<p id="submitted-message">
{cookieStore.get('mpa-message')?.value ?? 'none'}
</p>
)
}
'use client'
import { useActionState, useEffect, useState } from 'react'
import type { FormState } from './actions'
export function StateForm({
name,
action,
}: {
name: string
action: (previous: FormState, data: FormData) => Promise<FormState>
request?: Promise<string>
}) {
const [state, formAction] = useActionState(action, { count: 0, message: '' })
const [hydrated, setHydrated] = useState(false)
useEffect(() => setHydrated(true), [])
return (
<form action={formAction}>
<input name="message" defaultValue="Ada" />
<button id={`submit-${name}`}>Submit {name}</button>
<p id={`state-${name}`}>{`${state.count}:${state.message}`}</p>
{hydrated ? <p id={`hydrated-${name}`}>Hydrated</p> : null}
</form>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
experimental: { globalNotFound: true },
}
export default nextConfig
export default function GlobalNotFound() {
return (
<html>
<body>
<p id="global-not-found-message">Global MPA action not found</p>
</body>
</html>
)
}
import { FileRef, nextTestSetup } from 'e2e-utils'
import { join } from 'path'
import type { Page } from 'playwright'
import { load } from 'cheerio'
describe('mpa-server-action-html with global-not-found', () => {
const { next } = nextTestSetup({
files: __dirname,
overrideFiles: {
'next.config.ts': new FileRef(
join(__dirname, 'fixtures/global-next.config.ts')
),
'app/global-not-found.tsx': new FileRef(
join(__dirname, 'fixtures/global-not-found.tsx')
),
},
})
it('renders a complete global not-found document after an MPA form submission', async () => {
let page: Page
const browser = await next.browser('/', {
disableJavaScript: true,
beforePageLoad(value: Page) {
page = value
},
})
const pendingResponse = page!.waitForResponse(
(response) => response.request().method() === 'POST'
)
await browser.elementById('submit-not-found').click()
const response = await pendingResponse
expect(response.status()).toBe(404)
const html = await response.text()
expect(html).toMatch(/<!doctype html>/i)
expect(html).toMatch(/<html[\s>]/i)
expect(html).toMatch(/<body[\s>]/i)
expect(html).toEndWith('</html>')
const $ = load(html)
expect($('#global-not-found-message').text()).toBe(
'Global MPA action not found'
)
})
})
import { nextTestSetup } from 'e2e-utils'
import type { Page, Response } from 'playwright'
import { load } from 'cheerio'
import { retry } from 'next-test-utils'
describe('mpa-server-action-html', () => {
const { next } = nextTestSetup({ files: __dirname })
async function openPage(pathname = '/') {
let page: Page
const browser = await next.browser(pathname, {
disableJavaScript: true,
beforePageLoad(value: Page) {
page = value
},
})
return { browser, page: page! }
}
async function readDocument(response: Response, status = 200) {
expect(response.status()).toBe(status)
const html = await response.text()
expect(html).toMatch(/<!doctype html>/i)
expect(html).toMatch(/<html[\s>]/i)
expect(html).toMatch(/<body[\s>]/i)
expect(html).toEndWith('</html>')
const $ = load(html)
expect($('#static-shell').text()).toBe('MPA action page')
return $
}
it('returns a complete document after a plain action with bound arguments', async () => {
const { browser, page } = await openPage()
const pendingResponse = page.waitForResponse(
(response) => response.request().method() === 'POST'
)
await browser.elementById('submit-plain').click()
const $ = await readDocument(await pendingResponse)
expect($('#submitted-message').text()).toBe('bound:Ada')
})
it.each([
['/', 'static'],
['/dynamic-form', 'dynamic'],
['/data-only', 'data'],
['/blocking', 'blocking'],
])(
'renders returned form state in a complete document on %s',
async (pathname, name) => {
const { page } = await openPage(pathname)
for (const count of [1, 2]) {
const [response] = await Promise.all([
page.waitForResponse(
(response) => response.request().method() === 'POST'
),
page.locator(`#submit-${name}`).evaluate((button) => {
button.closest('form')!.requestSubmit()
}),
])
const $ = await readDocument(response)
expect($(`#state-${name}`).text()).toBe(`${count}:${name}:Ada`)
expect(await page.locator(`#state-${name}`).textContent()).toBe(
`${count}:${name}:Ada`
)
}
}
)
it('returns a complete not-found document after an MPA form submission', async () => {
const { browser, page } = await openPage()
const pendingResponse = page.waitForResponse(
(response) => response.request().method() === 'POST'
)
await browser.elementById('submit-not-found').click()
const $ = await readDocument(await pendingResponse, 404)
expect($('#not-found-message').text()).toBe('MPA action not found')
})
// @force-gate !dev
it('reuses prerendered cache values from the RDC after an MPA form submission', async () => {
const { browser, page } = await openPage()
const initialLayout = await browser.elementById('layout-value').text()
const initialContent = await browser.elementById('content-value').text()
const pendingResponse = page.waitForResponse(
(response) => response.request().method() === 'POST'
)
await browser.elementById('submit-static').click()
const $ = await readDocument(await pendingResponse)
expect($('#layout-value').text()).toBe(initialLayout)
expect($('#content-value').text()).toBe(initialContent)
expect($('#state-static').text()).toBe('1:static:Ada')
})
it('uses fresh invalidated data while preserving unrelated cached values', async () => {
const { browser, page } = await openPage()
const initialLayout = await browser.elementById('layout-value').text()
const initialContent = await browser.elementById('content-value').text()
const pendingResponse = page.waitForResponse(
(response) => response.request().method() === 'POST'
)
await browser.elementById('submit-invalidate').click()
const $ = await readDocument(await pendingResponse)
expect($('#content-value').text()).not.toBe(initialContent)
expect($('#layout-value').text()).toBe(initialLayout)
expect($('#state-invalidate').text()).toBe('1:invalidate:Ada')
})
it('preserves form state through an MPA form submission, hydration, and a fetch action', async () => {
let page: Page
let releaseScripts: () => void
let notifyBlockedScript: () => void
let scriptsReleased = false
const scriptsReady = new Promise<void>((resolve) => {
releaseScripts = resolve
})
const scriptBlocked = new Promise<void>((resolve) => {
notifyBlockedScript = resolve
})
const browser = await next.browser('/', {
waitHydration: false,
waitUntil: 'commit',
async beforePageLoad(value: Page) {
page = value
await page.route('**/_next/**/*.js*', async (route) => {
if (!scriptsReleased) {
notifyBlockedScript!()
await scriptsReady
}
await route.continue().catch(() => {})
})
},
})
try {
await page!.locator('#submit-static').waitFor({ state: 'visible' })
await scriptBlocked
const pendingResponse = page!.waitForResponse(
(response) => response.request().method() === 'POST'
)
await page!.locator('#submit-static').click({ noWaitAfter: true })
const response = await pendingResponse
expect(response.request().headers()['next-action']).toBeUndefined()
const $ = await readDocument(response)
expect($('#state-static').text()).toBe('1:static:Ada')
scriptsReleased = true
releaseScripts!()
await browser.waitForElementByCss('#hydrated-static')
expect(await browser.elementById('state-static').text()).toBe(
'1:static:Ada'
)
const pendingFetch = page!.waitForResponse(
(response) => response.request().method() === 'POST'
)
await browser.elementById('submit-static').click()
const fetchResponse = await pendingFetch
expect(fetchResponse.request().headers()['next-action']).toEqual(
expect.any(String)
)
expect(fetchResponse.headers()['content-type']).toContain(
'text/x-component'
)
await retry(async () => {
expect(await browser.elementById('state-static').text()).toBe(
'2:static:Ada'
)
})
} finally {
scriptsReleased = true
releaseScripts!()
}
})
})
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
}
export default nextConfig
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