Unverified Commit be9491e2 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Ensure there is only 1 render pass in concurrent rendering with getInitialProps…

Ensure there is only 1 render pass in concurrent rendering with getInitialProps in `_document` (#36352)

This PR makes sure `renderPage` calls `renderShell` in concurrent features, and `renderToString` if not.

Closes #36268, #36229.

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `yarn lint`
parent b8f7c520
...@@ -395,7 +395,6 @@ const useFlightResponse = createFlightHook() ...@@ -395,7 +395,6 @@ const useFlightResponse = createFlightHook()
// Create the wrapper component for a Flight stream. // Create the wrapper component for a Flight stream.
function createServerComponentRenderer( function createServerComponentRenderer(
AppMod: any,
ComponentMod: any, ComponentMod: any,
{ {
cachePrefix, cachePrefix,
...@@ -415,10 +414,13 @@ function createServerComponentRenderer( ...@@ -415,10 +414,13 @@ function createServerComponentRenderer(
globalThis.__webpack_require__ = ComponentMod.__next_rsc__.__webpack_require__ globalThis.__webpack_require__ = ComponentMod.__next_rsc__.__webpack_require__
const Component = interopDefault(ComponentMod) const Component = interopDefault(ComponentMod)
function ServerComponentWrapper(props: any) { function ServerComponentWrapper({ App, router, ...props }: any) {
const id = (React as any).useId() const id = (React as any).useId()
const reqStream: ReadableStream<Uint8Array> = renderToReadableStream( const reqStream: ReadableStream<Uint8Array> = renderToReadableStream(
renderFlight(AppMod, ComponentMod, props), <App>
<Component {...props} />
</App>,
serverComponentManifest serverComponentManifest
) )
...@@ -520,7 +522,7 @@ export async function renderToHTML( ...@@ -520,7 +522,7 @@ export async function renderToHTML(
if (isServerComponent) { if (isServerComponent) {
serverComponentsInlinedTransformStream = new TransformStream() serverComponentsInlinedTransformStream = new TransformStream()
const search = urlQueryToSearchParams(query).toString() const search = urlQueryToSearchParams(query).toString()
Component = createServerComponentRenderer(AppMod, ComponentMod, { Component = createServerComponentRenderer(ComponentMod, {
cachePrefix: pathname + (search ? `?${search}` : ''), cachePrefix: pathname + (search ? `?${search}` : ''),
inlinedTransformStream: serverComponentsInlinedTransformStream, inlinedTransformStream: serverComponentsInlinedTransformStream,
staticTransformStream: serverComponentsPageDataTransformStream, staticTransformStream: serverComponentsPageDataTransformStream,
...@@ -1311,11 +1313,24 @@ export async function renderToHTML( ...@@ -1311,11 +1313,24 @@ export async function renderToHTML(
} }
} }
async function documentInitialProps() { async function documentInitialProps(
renderShell?: ({
EnhancedApp,
EnhancedComponent,
}: {
EnhancedApp?: AppType
EnhancedComponent?: NextComponentType
}) => Promise<void>
) {
const renderPage: RenderPage = ( const renderPage: RenderPage = (
options: ComponentsEnhancer = {} options: ComponentsEnhancer = {}
): RenderPageResult | Promise<RenderPageResult> => { ): RenderPageResult | Promise<RenderPageResult> => {
if (ctx.err && ErrorDebug) { if (ctx.err && ErrorDebug) {
// Always start rendering the shell even if there's an error.
if (renderShell) {
renderShell({})
}
const html = ReactDOMServer.renderToString( const html = ReactDOMServer.renderToString(
<Body> <Body>
<ErrorDebug error={ctx.err} /> <ErrorDebug error={ctx.err} />
...@@ -1333,6 +1348,14 @@ export async function renderToHTML( ...@@ -1333,6 +1348,14 @@ export async function renderToHTML(
const { App: EnhancedApp, Component: EnhancedComponent } = const { App: EnhancedApp, Component: EnhancedComponent } =
enhanceComponents(options, App, Component) enhanceComponents(options, App, Component)
if (renderShell) {
return renderShell({ EnhancedApp, EnhancedComponent }).then(() => {
// When using concurrent features, we don't have or need the full
// html so it's fine to return nothing here.
return { html: '', head }
})
}
const html = ReactDOMServer.renderToString( const html = ReactDOMServer.renderToString(
<Body> <Body>
<AppContainerWithIsomorphicFiberStructure> <AppContainerWithIsomorphicFiberStructure>
...@@ -1364,7 +1387,13 @@ export async function renderToHTML( ...@@ -1364,7 +1387,13 @@ export async function renderToHTML(
return { docProps, documentCtx } return { docProps, documentCtx }
} }
const renderContent = () => { const renderContent = ({
EnhancedApp,
EnhancedComponent,
}: {
EnhancedApp?: AppType
EnhancedComponent?: NextComponentType
} = {}) => {
return ctx.err && ErrorDebug ? ( return ctx.err && ErrorDebug ? (
<Body> <Body>
<ErrorDebug error={ctx.err} /> <ErrorDebug error={ctx.err} />
...@@ -1372,12 +1401,16 @@ export async function renderToHTML( ...@@ -1372,12 +1401,16 @@ export async function renderToHTML(
) : ( ) : (
<Body> <Body>
<AppContainerWithIsomorphicFiberStructure> <AppContainerWithIsomorphicFiberStructure>
{isServerComponent && !!AppMod.__next_rsc__ ? ( {isServerComponent
// _app.server.js is used. ? React.createElement(EnhancedComponent || Component, {
<Component {...props.pageProps} /> App: EnhancedApp || App,
) : ( ...props.pageProps,
<App {...props} Component={Component} router={router} /> })
)} : React.createElement(EnhancedApp || App, {
...props,
Component: EnhancedComponent || Component,
router,
})}
</AppContainerWithIsomorphicFiberStructure> </AppContainerWithIsomorphicFiberStructure>
</Body> </Body>
) )
...@@ -1419,13 +1452,23 @@ export async function renderToHTML( ...@@ -1419,13 +1452,23 @@ export async function renderToHTML(
} }
} }
} else { } else {
// We start rendering the shell earlier, before returning the head tags let renderStream: ReadableStream<Uint8Array> & {
// to `documentResult`. allReady?: Promise<void> | undefined
const content = renderContent() }
const renderStream = await renderToInitialStream({
ReactDOMServer, const renderShell = async ({
element: content, EnhancedApp,
}) EnhancedComponent,
}: {
EnhancedApp?: AppType
EnhancedComponent?: NextComponentType
} = {}) => {
const content = renderContent({ EnhancedApp, EnhancedComponent })
renderStream = await renderToInitialStream({
ReactDOMServer,
element: content,
})
}
const bodyResult = async (suffix: string) => { const bodyResult = async (suffix: string) => {
// this must be called inside bodyResult so appWrappers is // this must be called inside bodyResult so appWrappers is
...@@ -1494,10 +1537,18 @@ export async function renderToHTML( ...@@ -1494,10 +1537,18 @@ export async function renderToHTML(
!Document.getInitialProps !Document.getInitialProps
) )
const documentInitialPropsRes = hasDocumentGetInitialProps // If it has getInitialProps, we will render the shell in `renderPage`.
? await documentInitialProps() // Otherwise we do it right now.
: {} let documentInitialPropsRes:
if (documentInitialPropsRes === null) return null | {}
| Awaited<ReturnType<typeof documentInitialProps>>
if (hasDocumentGetInitialProps) {
documentInitialPropsRes = await documentInitialProps(renderShell)
if (documentInitialPropsRes === null) return null
} else {
await renderShell()
documentInitialPropsRes = {}
}
const { docProps } = (documentInitialPropsRes as any) || {} const { docProps } = (documentInitialPropsRes as any) || {}
const documentElement = () => { const documentElement = () => {
......
...@@ -73,4 +73,15 @@ describe('styled-components SWC transform', () => { ...@@ -73,4 +73,15 @@ describe('styled-components SWC transform', () => {
expect(html).toContain('background:transparent') expect(html).toContain('background:transparent')
expect(html).toContain('color:white') expect(html).toContain('color:white')
}) })
it('should only render once on the server per request', async () => {
const outputs = []
next.on('stdout', (args) => {
outputs.push(args)
})
await renderViaHTTP(next.url, '/')
expect(
outputs.filter((output) => output.trim() === '__render__').length
).toBe(1)
})
}) })
...@@ -21,6 +21,7 @@ const Button = styled.a` ...@@ -21,6 +21,7 @@ const Button = styled.a`
` `
export default function Home() { export default function Home() {
console.log('__render__')
return ( return (
<div> <div>
<Button <Button
......
...@@ -5,6 +5,7 @@ export default function Index() { ...@@ -5,6 +5,7 @@ export default function Index() {
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
window.didHydrate = true window.didHydrate = true
} }
console.log('__render__')
return ( return (
<div> <div>
<p id="react-dom-version">{ReactDOM.version}</p> <p id="react-dom-version">{ReactDOM.version}</p>
......
...@@ -5,6 +5,11 @@ import cheerio from 'cheerio' ...@@ -5,6 +5,11 @@ import cheerio from 'cheerio'
import { renderViaHTTP } from 'next-test-utils' import { renderViaHTTP } from 'next-test-utils'
export default (context, env) => { export default (context, env) => {
it('should only render once in SSR', async () => {
await renderViaHTTP(context.appPort, '/')
expect([...context.stdout.matchAll(/__render__/g)].length).toBe(1)
})
it('no warnings for image related link props', async () => { it('no warnings for image related link props', async () => {
await renderViaHTTP(context.appPort, '/') await renderViaHTTP(context.appPort, '/')
expect(context.stderr).not.toContain('Warning: Invalid DOM property') expect(context.stderr).not.toContain('Warning: Invalid DOM property')
......
...@@ -758,6 +758,10 @@ function runSuite(suiteName, context, options) { ...@@ -758,6 +758,10 @@ function runSuite(suiteName, context, options) {
const onStderr = (msg) => { const onStderr = (msg) => {
context.stderr += msg context.stderr += msg
} }
context.stdout = ''
const onStdout = (msg) => {
context.stdout += msg
}
if (env === 'prod') { if (env === 'prod') {
context.appPort = await findPort() context.appPort = await findPort()
const { stdout, stderr, code } = await nextBuild(appDir, [], { const { stdout, stderr, code } = await nextBuild(appDir, [], {
...@@ -769,11 +773,13 @@ function runSuite(suiteName, context, options) { ...@@ -769,11 +773,13 @@ function runSuite(suiteName, context, options) {
context.code = code context.code = code
context.server = await nextStart(context.appDir, context.appPort, { context.server = await nextStart(context.appDir, context.appPort, {
onStderr, onStderr,
onStdout,
}) })
} else if (env === 'dev') { } else if (env === 'dev') {
context.appPort = await findPort() context.appPort = await findPort()
context.server = await launchApp(context.appDir, context.appPort, { context.server = await launchApp(context.appDir, context.appPort, {
onStderr, onStderr,
onStdout,
}) })
} }
}) })
......
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