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

Drop legacy React DOM Server in Edge runtime (#40018)

When possible (`ReactRoot` enabled), we always use
`renderToReadableStream` to render the element to string and drop all
`renderToString` and `renderToStaticMarkup` usages. Since this is always
true for the Edge Runtime (which requires React 18+), so we can safely
eliminate the `./cjs/react-dom-server-legacy.browser.production.min.js`
module there
([ref](https://unpkg.com/browse/react-dom@18.2.0/server.browser.js)).

This reduces the gzipped bundle by 11kb (~9%). Let me know if there's
any concern or it's too hacky.

<img width="904" alt="image"
src="https://user-images.githubusercontent.com/11064311/192544933-298e3638-13ba-436d-9bcb-42dfb1224025.png">


## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] 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 `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
Co-authored-by: 's avatarJimmy Lai <laijimmy0@gmail.com>
parent c1c95bfd
...@@ -1186,6 +1186,10 @@ export default async function getBaseWebpackConfig( ...@@ -1186,6 +1186,10 @@ export default async function getBaseWebpackConfig(
'@builder.io/partytown': '{}', '@builder.io/partytown': '{}',
'next/dist/compiled/etag': '{}', 'next/dist/compiled/etag': '{}',
'next/dist/compiled/chalk': '{}', 'next/dist/compiled/chalk': '{}',
'./cjs/react-dom-server-legacy.browser.production.min.js':
'{}',
'./cjs/react-dom-server-legacy.browser.development.js':
'{}',
'react-dom': '{}', 'react-dom': '{}',
}, },
handleWebpackExtenalForEdgeRuntime, handleWebpackExtenalForEdgeRuntime,
......
...@@ -17,6 +17,7 @@ import { ...@@ -17,6 +17,7 @@ import {
renderToInitialStream, renderToInitialStream,
createBufferedTransformStream, createBufferedTransformStream,
continueFromInitialStream, continueFromInitialStream,
streamToString,
} from './node-web-streams-helper' } from './node-web-streams-helper'
import { ESCAPE_REGEX, htmlEscapeJsonString } from './htmlescape' import { ESCAPE_REGEX, htmlEscapeJsonString } from './htmlescape'
import { shouldUseReactRoot } from './utils' import { shouldUseReactRoot } from './utils'
...@@ -595,6 +596,13 @@ function headersWithoutFlight(headers: IncomingHttpHeaders) { ...@@ -595,6 +596,13 @@ function headersWithoutFlight(headers: IncomingHttpHeaders) {
return newHeaders return newHeaders
} }
async function renderToString(element: React.ReactElement) {
if (!shouldUseReactRoot) return ReactDOMServer.renderToString(element)
const renderStream = await ReactDOMServer.renderToReadableStream(element)
await renderStream.allReady
return streamToString(renderStream)
}
export async function renderToHTMLOrFlight( export async function renderToHTMLOrFlight(
req: IncomingMessage, req: IncomingMessage,
res: ServerResponse, res: ServerResponse,
...@@ -1272,8 +1280,8 @@ export async function renderToHTMLOrFlight( ...@@ -1272,8 +1280,8 @@ export async function renderToHTMLOrFlight(
</FlushEffects> </FlushEffects>
) )
const flushEffectHandler = (): string => { const flushEffectHandler = (): Promise<string> => {
const flushed = ReactDOMServer.renderToString( const flushed = renderToString(
<>{Array.from(flushEffectsCallbacks).map((callback) => callback())}</> <>{Array.from(flushEffectsCallbacks).map((callback) => callback())}</>
) )
return flushed return flushed
......
...@@ -44,7 +44,7 @@ import { ...@@ -44,7 +44,7 @@ import {
getCookieParser, getCookieParser,
checkIsManualRevalidate, checkIsManualRevalidate,
} from './api-utils' } from './api-utils'
import * as envConfig from '../shared/lib/runtime-config' import { setConfig } from '../shared/lib/runtime-config'
import Router from './router' import Router from './router'
import { setRevalidateHeaders } from './send-payload/revalidate-headers' import { setRevalidateHeaders } from './send-payload/revalidate-headers'
...@@ -67,7 +67,6 @@ import { removePathPrefix } from '../shared/lib/router/utils/remove-path-prefix' ...@@ -67,7 +67,6 @@ import { removePathPrefix } from '../shared/lib/router/utils/remove-path-prefix'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { getRouteMatcher } from '../shared/lib/router/utils/route-matcher' import { getRouteMatcher } from '../shared/lib/router/utils/route-matcher'
import { getRouteRegex } from '../shared/lib/router/utils/route-regex' import { getRouteRegex } from '../shared/lib/router/utils/route-regex'
import { getLocaleRedirect } from '../shared/lib/i18n/get-locale-redirect'
import { getHostname } from '../shared/lib/get-hostname' import { getHostname } from '../shared/lib/get-hostname'
import { parseUrl as parseUrlUtil } from '../shared/lib/router/utils/parse-url' import { parseUrl as parseUrlUtil } from '../shared/lib/router/utils/parse-url'
import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info' import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info'
...@@ -415,7 +414,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -415,7 +414,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
} }
// Initialize next/config with the environment configuration // Initialize next/config with the environment configuration
envConfig.setConfig({ setConfig({
serverRuntimeConfig, serverRuntimeConfig,
publicRuntimeConfig, publicRuntimeConfig,
}) })
...@@ -668,7 +667,14 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -668,7 +667,14 @@ export default abstract class Server<ServerOptions extends Options = Options> {
} }
} }
if (!this.minimalMode && defaultLocale) { if (
// Edge runtime always has minimal mode enabled.
process.env.NEXT_RUNTIME !== 'edge' &&
!this.minimalMode &&
defaultLocale
) {
const { getLocaleRedirect } =
require('../shared/lib/i18n/get-locale-redirect') as typeof import('../shared/lib/i18n/get-locale-redirect')
const redirect = getLocaleRedirect({ const redirect = getLocaleRedirect({
defaultLocale, defaultLocale,
domainLocale, domainLocale,
...@@ -1367,6 +1373,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1367,6 +1373,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
// getStaticPaths, then finish the data request on the client-side. // getStaticPaths, then finish the data request on the client-side.
// //
if ( if (
process.env.NEXT_RUNTIME !== 'edge' &&
this.minimalMode !== true && this.minimalMode !== true &&
fallbackMode !== 'blocking' && fallbackMode !== 'blocking' &&
ssgCacheKey && ssgCacheKey &&
......
...@@ -124,11 +124,11 @@ export function createBufferedTransformStream( ...@@ -124,11 +124,11 @@ export function createBufferedTransformStream(
} }
export function createFlushEffectStream( export function createFlushEffectStream(
handleFlushEffect: () => string handleFlushEffect: () => Promise<string>
): TransformStream<Uint8Array, Uint8Array> { ): TransformStream<Uint8Array, Uint8Array> {
return new TransformStream({ return new TransformStream({
transform(chunk, controller) { async transform(chunk, controller) {
const flushedChunk = encodeText(handleFlushEffect()) const flushedChunk = encodeText(await handleFlushEffect())
controller.enqueue(flushedChunk) controller.enqueue(flushedChunk)
controller.enqueue(chunk) controller.enqueue(chunk)
...@@ -149,17 +149,17 @@ export function renderToInitialStream({ ...@@ -149,17 +149,17 @@ export function renderToInitialStream({
} }
export function createHeadInjectionTransformStream( export function createHeadInjectionTransformStream(
inject: () => string inject: () => Promise<string>
): TransformStream<Uint8Array, Uint8Array> { ): TransformStream<Uint8Array, Uint8Array> {
let injected = false let injected = false
return new TransformStream({ return new TransformStream({
transform(chunk, controller) { async transform(chunk, controller) {
const content = decodeText(chunk) const content = decodeText(chunk)
let index let index
if (!injected && (index = content.indexOf('</head')) !== -1) { if (!injected && (index = content.indexOf('</head')) !== -1) {
injected = true injected = true
const injectedContent = const injectedContent =
content.slice(0, index) + inject() + content.slice(index) content.slice(0, index) + (await inject()) + content.slice(index)
controller.enqueue(encodeText(injectedContent)) controller.enqueue(encodeText(injectedContent))
} else { } else {
controller.enqueue(chunk) controller.enqueue(chunk)
...@@ -269,7 +269,7 @@ export async function continueFromInitialStream( ...@@ -269,7 +269,7 @@ export async function continueFromInitialStream(
suffix?: string suffix?: string
dataStream?: ReadableStream<Uint8Array> dataStream?: ReadableStream<Uint8Array>
generateStaticHTML: boolean generateStaticHTML: boolean
flushEffectHandler?: () => string flushEffectHandler?: () => Promise<string>
flushEffectsToHead: boolean flushEffectsToHead: boolean
} }
): Promise<ReadableStream<Uint8Array>> { ): Promise<ReadableStream<Uint8Array>> {
...@@ -288,11 +288,13 @@ export async function continueFromInitialStream( ...@@ -288,11 +288,13 @@ export async function continueFromInitialStream(
suffixUnclosed != null ? createDeferredSuffixStream(suffixUnclosed) : null, suffixUnclosed != null ? createDeferredSuffixStream(suffixUnclosed) : null,
dataStream ? createInlineDataStream(dataStream) : null, dataStream ? createInlineDataStream(dataStream) : null,
suffixUnclosed != null ? createSuffixStream(closeTag) : null, suffixUnclosed != null ? createSuffixStream(closeTag) : null,
createHeadInjectionTransformStream(() => { createHeadInjectionTransformStream(async () => {
// TODO-APP: Inject flush effects to end of head in app layout rendering, to avoid // TODO-APP: Inject flush effects to end of head in app layout rendering, to avoid
// hydration errors. Remove this once it's ready to be handled by react itself. // hydration errors. Remove this once it's ready to be handled by react itself.
const flushEffectsContent = const flushEffectsContent =
flushEffectHandler && flushEffectsToHead ? flushEffectHandler() : '' flushEffectHandler && flushEffectsToHead
? await flushEffectHandler()
: ''
return flushEffectsContent return flushEffectsContent
}), }),
].filter(nonNullable) ].filter(nonNullable)
......
...@@ -108,6 +108,18 @@ function noRouter() { ...@@ -108,6 +108,18 @@ function noRouter() {
throw new Error(message) throw new Error(message)
} }
async function renderToString(element: React.ReactElement) {
if (!shouldUseReactRoot) return ReactDOMServer.renderToString(element)
const renderStream = await ReactDOMServer.renderToReadableStream(element)
await renderStream.allReady
return streamToString(renderStream)
}
async function renderToStaticMarkup(element: React.ReactElement) {
if (!shouldUseReactRoot) return ReactDOMServer.renderToStaticMarkup(element)
return renderToString(element)
}
class ServerRouter implements NextRouter { class ServerRouter implements NextRouter {
route: string route: string
pathname: string pathname: string
...@@ -1148,16 +1160,16 @@ export async function renderToHTML( ...@@ -1148,16 +1160,16 @@ export async function renderToHTML(
_Component: NextComponentType _Component: NextComponentType
) => Promise<ReactReadableStream> ) => Promise<ReactReadableStream>
) { ) {
const renderPage: RenderPage = ( const renderPage: RenderPage = async (
options: ComponentsEnhancer = {} options: ComponentsEnhancer = {}
): RenderPageResult | Promise<RenderPageResult> => { ): Promise<RenderPageResult> => {
if (ctx.err && ErrorDebug) { if (ctx.err && ErrorDebug) {
// Always start rendering the shell even if there's an error. // Always start rendering the shell even if there's an error.
if (renderShell) { if (renderShell) {
renderShell(App, Component) renderShell(App, Component)
} }
const html = ReactDOMServer.renderToString( const html = await renderToString(
<Body> <Body>
<ErrorDebug error={ctx.err} /> <ErrorDebug error={ctx.err} />
</Body> </Body>
...@@ -1184,7 +1196,7 @@ export async function renderToHTML( ...@@ -1184,7 +1196,7 @@ export async function renderToHTML(
) )
} }
const html = ReactDOMServer.renderToString( const html = await renderToString(
<Body> <Body>
<AppContainerWithIsomorphicFiberStructure> <AppContainerWithIsomorphicFiberStructure>
{renderPageTree(EnhancedApp, EnhancedComponent, { {renderPageTree(EnhancedApp, EnhancedComponent, {
...@@ -1256,7 +1268,7 @@ export async function renderToHTML( ...@@ -1256,7 +1268,7 @@ export async function renderToHTML(
// for non-concurrent rendering we need to ensure App is rendered // for non-concurrent rendering we need to ensure App is rendered
// before _document so that updateHead is called/collected before // before _document so that updateHead is called/collected before
// rendering _document's head // rendering _document's head
const result = ReactDOMServer.renderToString(content) const result = await renderToString(content)
const bodyResult = (suffix: string) => streamFromArray([result, suffix]) const bodyResult = (suffix: string) => streamFromArray([result, suffix])
const styles = jsxStyleRegistry.styles() const styles = jsxStyleRegistry.styles()
...@@ -1289,9 +1301,8 @@ export async function renderToHTML( ...@@ -1289,9 +1301,8 @@ export async function renderToHTML(
) => { ) => {
// this must be called inside bodyResult so appWrappers is // this must be called inside bodyResult so appWrappers is
// up to date when `wrapApp` is called // up to date when `wrapApp` is called
const flushEffectHandler = (): string => { const flushEffectHandler = async (): Promise<string> => {
const flushed = ReactDOMServer.renderToString(styledJsxFlushEffect()) return renderToString(styledJsxFlushEffect())
return flushed
} }
return continueFromInitialStream(initialStream, { return continueFromInitialStream(initialStream, {
...@@ -1459,7 +1470,7 @@ export async function renderToHTML( ...@@ -1459,7 +1470,7 @@ export async function renderToHTML(
</AmpStateContext.Provider> </AmpStateContext.Provider>
) )
const documentHTML = ReactDOMServer.renderToStaticMarkup(document) const documentHTML = await renderToStaticMarkup(document)
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
const nonRenderedComponents = [] const nonRenderedComponents = []
......
...@@ -8,6 +8,8 @@ import type { LoadComponentsReturnType } from './load-components' ...@@ -8,6 +8,8 @@ import type { LoadComponentsReturnType } from './load-components'
import { NoFallbackError, Options } from './base-server' import { NoFallbackError, Options } from './base-server'
import type { DynamicRoutes, PageChecker, Route } from './router' import type { DynamicRoutes, PageChecker, Route } from './router'
import type { NextConfig } from './config-shared' import type { NextConfig } from './config-shared'
import type { BaseNextRequest, BaseNextResponse } from './base-http'
import type { UrlWithParsedQuery } from 'url'
import BaseServer from './base-server' import BaseServer from './base-server'
import { byteLength } from './api-utils/web' import { byteLength } from './api-utils/web'
...@@ -19,8 +21,6 @@ import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-ass ...@@ -19,8 +21,6 @@ import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-ass
import { detectDomainLocale } from '../shared/lib/i18n/detect-domain-locale' import { detectDomainLocale } from '../shared/lib/i18n/detect-domain-locale'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash' import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
import type { BaseNextRequest, BaseNextResponse } from './base-http'
import type { UrlWithParsedQuery } from 'url'
interface WebServerOptions extends Options { interface WebServerOptions extends Options {
webServerConfig: { webServerConfig: {
......
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