Skip to content

Commit

Permalink
Use renderToString for flush effects (#35999)
Browse files Browse the repository at this point in the history
Use render to string call to render flush effects instead of rendering with stream plus converting to string
  • Loading branch information
huozhi committed Apr 8, 2022
1 parent d8623bb commit eddf171
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 19 deletions.
10 changes: 5 additions & 5 deletions packages/next/server/node-web-streams-helper.ts
Expand Up @@ -118,11 +118,11 @@ export function createBufferedTransformStream(): TransformStream<
}

export function createFlushEffectStream(
handleFlushEffect: () => Promise<string>
handleFlushEffect: () => string
): TransformStream<Uint8Array, Uint8Array> {
return new TransformStream({
async transform(chunk, controller) {
const flushedChunk = encodeText(await handleFlushEffect())
transform(chunk, controller) {
const flushedChunk = encodeText(handleFlushEffect())

controller.enqueue(flushedChunk)
controller.enqueue(chunk)
Expand Down Expand Up @@ -154,7 +154,7 @@ export async function continueFromInitialStream({
suffix?: string
dataStream?: ReadableStream<Uint8Array>
generateStaticHTML: boolean
flushEffectHandler?: () => Promise<string>
flushEffectHandler?: () => string
renderStream: ReadableStream<Uint8Array> & {
allReady?: Promise<void>
}
Expand Down Expand Up @@ -193,7 +193,7 @@ export async function renderToStream({
suffix?: string
dataStream?: ReadableStream<Uint8Array>
generateStaticHTML: boolean
flushEffectHandler?: () => Promise<string>
flushEffectHandler?: () => string
}): Promise<ReadableStream<Uint8Array>> {
const renderStream = await renderToInitialStream({ ReactDOMServer, element })
return continueFromInitialStream({
Expand Down
23 changes: 9 additions & 14 deletions packages/next/server/render.tsx
Expand Up @@ -1430,25 +1430,20 @@ export async function renderToHTML(

const bodyResult = async (suffix: string) => {
// this must be called inside bodyResult so appWrappers is
// up to date when getWrappedApp is called
// up to date when `wrapApp` is called

const flushEffectHandler = async () => {
const flushEffectHandler = (): string => {
const allFlushEffects = [
styledJsxFlushEffect,
...(flushEffects || []),
]
const flushEffectStream = await renderToStream({
ReactDOMServer,
element: (
<>
{allFlushEffects.map((flushEffect, i) => (
<React.Fragment key={i}>{flushEffect()}</React.Fragment>
))}
</>
),
generateStaticHTML: true,
})
const flushed = await streamToString(flushEffectStream)
const flushed = ReactDOMServer.renderToString(
<>
{allFlushEffects.map((flushEffect, i) => (
<React.Fragment key={i}>{flushEffect()}</React.Fragment>
))}
</>
)
return flushed
}

Expand Down

0 comments on commit eddf171

Please sign in to comment.