Unverified Commit 0b1d5e17 authored by Gerald Monaco's avatar Gerald Monaco Committed by GitHub

Use `react-dom/server.browser` in Node.js (#33950)

Instead of branching rendering based on Node.js and browser/web runtimes, we should just use the web version for now, which can run as-is on versions >=16.5.0 of Node.js, polyfilling `ReadableStream` on older versions when necessary.

There are a few potential downsides to this, as React is less able to optimize flushing and execution. We can revisit that in the future though if desired.
parent 502a869a
...@@ -610,14 +610,6 @@ export default async function getBaseWebpackConfig( ...@@ -610,14 +610,6 @@ export default async function getBaseWebpackConfig(
} }
: {}), : {}),
...(webServerRuntime
? {
'react-dom/server': dev
? 'react-dom/cjs/react-dom-server.browser.development'
: 'react-dom/cjs/react-dom-server.browser.production.min',
}
: {}),
setimmediate: 'next/dist/compiled/setimmediate', setimmediate: 'next/dist/compiled/setimmediate',
}, },
...(targetWeb ...(targetWeb
......
import { ReadableStream } from './web/sandbox/readable-stream'
// Polyfill ReadableStream in the Node.js environment
if (!global.ReadableStream) {
global.ReadableStream = ReadableStream
}
import type { ServerResponse } from 'http' import type { ServerResponse } from 'http'
import type { Writable } from 'stream'
export type NodeWritablePiper = ( export type ResultPiper = (
res: Writable, push: (chunks: Uint8Array[]) => void,
next: (err?: Error) => void next: (err?: Error) => void
) => void ) => void
export default class RenderResult { export default class RenderResult {
_result: string | NodeWritablePiper _result: string | ResultPiper
constructor(response: string | NodeWritablePiper) { constructor(response: string | ResultPiper) {
this._result = response this._result = response
} }
...@@ -29,8 +28,35 @@ export default class RenderResult { ...@@ -29,8 +28,35 @@ export default class RenderResult {
) )
} }
const response = this._result const response = this._result
const flush =
typeof (res as any).flush === 'function'
? () => (res as any).flush()
: () => {}
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
response(res, (err) => (err ? reject(err) : resolve())) let fatalError = false
response(
(chunks) => {
// The state of the stream is non-deterministic after
// writing, so any error becomes fatal.
fatalError = true
res.cork()
chunks.forEach((chunk) => res.write(chunk))
res.uncork()
flush()
},
(err) => {
if (err) {
if (fatalError) {
res.destroy(err)
}
reject(err)
} else {
res.end()
resolve()
}
}
)
}) })
} }
......
This diff is collapsed.
...@@ -146,11 +146,13 @@ export default class NextWebServer extends BaseServer { ...@@ -146,11 +146,13 @@ export default class NextWebServer extends BaseServer {
): Promise<void> { ): Promise<void> {
// @TODO // @TODO
const writer = res.transformStream.writable.getWriter() const writer = res.transformStream.writable.getWriter()
const encoder = new TextEncoder()
options.result.pipe({ options.result.pipe({
write: (str: string) => writer.write(encoder.encode(str)), write: (chunk: Uint8Array) => writer.write(chunk),
end: () => writer.close(), end: () => writer.close(),
// Not implemented: cork/uncork/on/removeListener destroy: (err: Error) => writer.abort(err),
cork: () => {},
uncork: () => {},
// Not implemented: on/removeListener
} as any) } as any)
// To prevent Safari's bfcache caching the "shell", we have to add the // To prevent Safari's bfcache caching the "shell", we have to add the
......
import { Crypto as WebCrypto } from 'next/dist/compiled/@peculiar/webcrypto' import { Crypto as WebCrypto } from 'next/dist/compiled/@peculiar/webcrypto'
import { CryptoKey } from 'next/dist/compiled/@peculiar/webcrypto' import { CryptoKey } from 'next/dist/compiled/@peculiar/webcrypto'
import { TransformStream } from 'next/dist/compiled/web-streams-polyfill'
import { v4 as uuid } from 'next/dist/compiled/uuid' import { v4 as uuid } from 'next/dist/compiled/uuid'
import { ReadableStream } from './readable-stream'
import crypto from 'crypto' import crypto from 'crypto'
...@@ -13,76 +13,9 @@ export function btoa(str: string) { ...@@ -13,76 +13,9 @@ export function btoa(str: string) {
return Buffer.from(str, 'binary').toString('base64') return Buffer.from(str, 'binary').toString('base64')
} }
export { CryptoKey } export { CryptoKey, ReadableStream }
export class Crypto extends WebCrypto { export class Crypto extends WebCrypto {
// @ts-ignore Remove once types are updated and we deprecate node 12 // @ts-ignore Remove once types are updated and we deprecate node 12
randomUUID = crypto.randomUUID || uuid randomUUID = crypto.randomUUID || uuid
} }
export class ReadableStream<T> {
constructor(opts: UnderlyingSource = {}) {
let closed = false
let pullPromise: any
let transformController: TransformStreamDefaultController
const { readable, writable } = new TransformStream(
{
start: (controller: TransformStreamDefaultController) => {
transformController = controller
},
},
undefined,
{
highWaterMark: 1,
}
)
const writer = writable.getWriter()
const encoder = new TextEncoder()
const controller: ReadableStreamController<T> = {
get desiredSize() {
return transformController.desiredSize
},
close: () => {
if (!closed) {
closed = true
writer.close()
}
},
enqueue: (chunk: T) => {
writer.write(typeof chunk === 'string' ? encoder.encode(chunk) : chunk)
pull()
},
error: (reason: any) => {
transformController.error(reason)
},
}
const pull = () => {
if (opts.pull) {
if (!pullPromise) {
pullPromise = Promise.resolve().then(() => {
pullPromise = 0
opts.pull!(controller)
})
}
}
}
if (opts.start) {
opts.start(controller)
}
if (opts.cancel) {
readable.cancel = (reason: any) => {
opts.cancel!(reason)
return readable.cancel(reason)
}
}
pull()
return readable
}
}
import { TransformStream } from 'next/dist/compiled/web-streams-polyfill'
export class ReadableStream<T> {
constructor(opts: UnderlyingSource = {}) {
let closed = false
let pullPromise: any
let transformController: TransformStreamDefaultController
const { readable, writable } = new TransformStream(
{
start: (controller: TransformStreamDefaultController) => {
transformController = controller
},
},
undefined,
{
highWaterMark: 1,
}
)
const writer = writable.getWriter()
const encoder = new TextEncoder()
const controller: ReadableStreamController<T> = {
get desiredSize() {
return transformController.desiredSize
},
close: () => {
if (!closed) {
closed = true
writer.close()
}
},
enqueue: (chunk: T) => {
writer.write(typeof chunk === 'string' ? encoder.encode(chunk) : chunk)
pull()
},
error: (reason: any) => {
transformController.error(reason)
},
}
const pull = () => {
if (opts.pull) {
if (!pullPromise) {
pullPromise = Promise.resolve().then(() => {
pullPromise = 0
opts.pull!(controller)
})
}
}
}
if (opts.start) {
opts.start(controller)
}
if (opts.cancel) {
readable.cancel = (reason: any) => {
opts.cancel!(reason)
return readable.cancel(reason)
}
}
pull()
return readable
}
}
...@@ -4,6 +4,7 @@ const hookPropertyMap = new Map([ ...@@ -4,6 +4,7 @@ const hookPropertyMap = new Map([
['react', 'react-18'], ['react', 'react-18'],
['react-dom', 'react-dom-18'], ['react-dom', 'react-dom-18'],
['react-dom/server', 'react-dom-18/server'], ['react-dom/server', 'react-dom-18/server'],
['react-dom/server.browser', 'react-dom-18/server.browser'],
]) ])
const resolveFilename = mod._resolveFilename const resolveFilename = mod._resolveFilename
......
...@@ -13,6 +13,7 @@ module.exports = function withReact18(config) { ...@@ -13,6 +13,7 @@ module.exports = function withReact18(config) {
alias['react'] = 'react-18' alias['react'] = 'react-18'
alias['react-dom'] = 'react-dom-18' alias['react-dom'] = 'react-dom-18'
alias['react-dom/server'] = 'react-dom-18/server' alias['react-dom/server'] = 'react-dom-18/server'
alias['react-dom/server.browser'] = 'react-dom-18/server.browser'
return webpackConfig return webpackConfig
} }
......
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