Unverified Commit 0dba1c69 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

Allow SSR to finish microtasky work before flushing (#86311)

In a dynamic Fizz (SSR) render, rendering work is initially scheduled using microtasks, and a flush will be attempted when the stream gets pulled:
https://github.com/facebook/react/blob/8ac5f4eb3601f7381462f8b74ecf24d47259cc20/packages/react-dom/src/server/ReactDOMFizzServerNode.js#L386-L389
This can cause streaming metadata to flake between appearing in `<head>` and `<body>` depending on if whether it had enough microtasks to render before the flush occurred.
In general, if something is async, but available after a couple microtasks, then we shouldn't bother streaming it, it should just go into the initial HTML. We achieve this by waiting a task before allowing the stream to get pulled, which allows all the microtasky work to finish without delaying the response too much.
parent f0a1a69a
......@@ -2,7 +2,11 @@ import type { ReactDOMServerReadableStream } from 'react-dom/server'
import { getTracer } from '../lib/trace/tracer'
import { AppRenderSpan } from '../lib/trace/constants'
import { DetachedPromise } from '../../lib/detached-promise'
import { scheduleImmediate, atLeastOneTask } from '../../lib/scheduler'
import {
scheduleImmediate,
atLeastOneTask,
waitAtLeastOneReactRenderTask,
} from '../../lib/scheduler'
import { ENCODED_TAGS } from './encoded-tags'
import {
indexOfUint8Array,
......@@ -797,9 +801,13 @@ export async function continueFizzStream(
// Suffix itself might contain close tags at the end, so we need to split it.
const suffixUnclosed = suffix ? suffix.split(CLOSE_TAG, 1)[0] : null
// If we're generating static HTML we need to wait for it to resolve before continuing.
if (isStaticGeneration) {
// If we're generating static HTML we need to wait for it to resolve before continuing.
await renderStream.allReady
} else {
// Otherwise, we want to make sure Fizz is done with all microtasky work
// before we start pulling the stream and cause a flush.
await waitAtLeastOneReactRenderTask()
}
return chainTransformers(renderStream, [
......
......@@ -18,8 +18,9 @@ export default async function Page() {
export async function generateMetadata() {
await connection()
// Delay until after the shell is flushed so that the tags end up in the body.
await new Promise((resolve) => setTimeout(resolve, 10))
return {
// This long text description will lead to the metadata being inserted after the head tag.
description: 'long text description'.repeat(1000),
icons: {
icon: `/heart.png`,
......
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