Unverified Commit b0c1697f authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

Fix hydration errors caused by root ErrorOverlay (#53216)

A bug was introduced in #52843 that causes hydration issues -- this
fixes that by moving the previous logic into the existing `isError` path
that doesn't trigger a call to `hydrateRoot` ensuring we are only doing
this on the client tree

Fixes #53110 and Fixes #53006
Closes NEXT-1470
parent 66ffc3cd
...@@ -226,8 +226,6 @@ const StrictModeIfEnabled = process.env.__NEXT_STRICT_MODE_APP ...@@ -226,8 +226,6 @@ const StrictModeIfEnabled = process.env.__NEXT_STRICT_MODE_APP
: React.Fragment : React.Fragment
function Root({ children }: React.PropsWithChildren<{}>): React.ReactElement { function Root({ children }: React.PropsWithChildren<{}>): React.ReactElement {
const [hadRuntimeError, setHadRuntimeError] = React.useState(false)
if (process.env.__NEXT_ANALYTICS_ID) { if (process.env.__NEXT_ANALYTICS_ID) {
// eslint-disable-next-line react-hooks/rules-of-hooks // eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => { React.useEffect(() => {
...@@ -246,63 +244,6 @@ function Root({ children }: React.PropsWithChildren<{}>): React.ReactElement { ...@@ -246,63 +244,6 @@ function Root({ children }: React.PropsWithChildren<{}>): React.ReactElement {
}, []) }, [])
} }
if (process.env.NODE_ENV !== 'production') {
const ReactDevOverlay: typeof import('./components/react-dev-overlay/internal/ReactDevOverlay').default =
require('./components/react-dev-overlay/internal/ReactDevOverlay')
.default as typeof import('./components/react-dev-overlay/internal/ReactDevOverlay').default
const INITIAL_OVERLAY_STATE: typeof import('./components/react-dev-overlay/internal/error-overlay-reducer').INITIAL_OVERLAY_STATE =
require('./components/react-dev-overlay/internal/error-overlay-reducer').INITIAL_OVERLAY_STATE
const useWebsocket: typeof import('./components/react-dev-overlay/internal/helpers/use-websocket').useWebsocket =
require('./components/react-dev-overlay/internal/helpers/use-websocket').useWebsocket
// subscribe to hmr only if an error was captured, so that we don't have two hmr websockets active
// eslint-disable-next-line react-hooks/rules-of-hooks
const webSocketRef = useWebsocket(
process.env.__NEXT_ASSET_PREFIX || '',
hadRuntimeError
)
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => {
const handler = (event: MessageEvent) => {
let obj
try {
obj = JSON.parse(event.data)
} catch {}
if (!obj || !('action' in obj)) {
return
}
// minimal "hot reload" support for RSC errors
if (obj.action === 'serverComponentChanges' && hadRuntimeError) {
window.location.reload()
}
}
const websocket = webSocketRef.current
if (websocket) {
websocket.addEventListener('message', handler)
}
return () =>
websocket && websocket.removeEventListener('message', handler)
}, [webSocketRef, hadRuntimeError])
// if an error is thrown while rendering an RSC stream, this will catch it in dev
// and show the error overlay
return (
<ReactDevOverlay
state={INITIAL_OVERLAY_STATE}
onReactError={() => setHadRuntimeError(true)}
>
{children}
</ReactDevOverlay>
)
}
return children as React.ReactElement return children as React.ReactElement
} }
...@@ -385,7 +326,49 @@ export function hydrate() { ...@@ -385,7 +326,49 @@ export function hydrate() {
} }
if (isError) { if (isError) {
ReactDOMClient.createRoot(appElement as any, options).render(reactEl) if (process.env.NODE_ENV !== 'production') {
// if an error is thrown while rendering an RSC stream, this will catch it in dev
// and show the error overlay
const ReactDevOverlay: typeof import('./components/react-dev-overlay/internal/ReactDevOverlay').default =
require('./components/react-dev-overlay/internal/ReactDevOverlay')
.default as typeof import('./components/react-dev-overlay/internal/ReactDevOverlay').default
const INITIAL_OVERLAY_STATE: typeof import('./components/react-dev-overlay/internal/error-overlay-reducer').INITIAL_OVERLAY_STATE =
require('./components/react-dev-overlay/internal/error-overlay-reducer').INITIAL_OVERLAY_STATE
const getSocketUrl: typeof import('./components/react-dev-overlay/internal/helpers/get-socket-url').getSocketUrl =
require('./components/react-dev-overlay/internal/helpers/get-socket-url')
.getSocketUrl as typeof import('./components/react-dev-overlay/internal/helpers/get-socket-url').getSocketUrl
let errorTree = (
<ReactDevOverlay state={INITIAL_OVERLAY_STATE} onReactError={() => {}}>
{reactEl}
</ReactDevOverlay>
)
const socketUrl = getSocketUrl(process.env.__NEXT_ASSET_PREFIX || '')
const socket = new window.WebSocket(`${socketUrl}/_next/webpack-hmr`)
// add minimal "hot reload" support for RSC errors
const handler = (event: MessageEvent) => {
let obj
try {
obj = JSON.parse(event.data)
} catch {}
if (!obj || !('action' in obj)) {
return
}
if (obj.action === 'serverComponentChanges') {
window.location.reload()
}
}
socket.addEventListener('message', handler)
ReactDOMClient.createRoot(appElement as any, options).render(errorTree)
} else {
ReactDOMClient.createRoot(appElement as any, options).render(reactEl)
}
} else { } else {
React.startTransition(() => React.startTransition(() =>
(ReactDOMClient as any).hydrateRoot(appElement, reactEl, options) (ReactDOMClient as any).hydrateRoot(appElement, reactEl, options)
......
export function getSocketProtocol(assetPrefix: string): string {
let protocol = window.location.protocol
try {
// assetPrefix is a url
protocol = new URL(assetPrefix).protocol
} catch (_) {}
return protocol === 'http:' ? 'ws' : 'wss'
}
function getSocketProtocol(assetPrefix: string): string {
let protocol = window.location.protocol
try {
// assetPrefix is a url
protocol = new URL(assetPrefix).protocol
} catch (_) {}
return protocol === 'http:' ? 'ws' : 'wss'
}
export function getSocketUrl(assetPrefix: string): string {
const { hostname, port } = window.location
const protocol = getSocketProtocol(assetPrefix)
const normalizedAssetPrefix = assetPrefix.replace(/^\/+/, '')
let url = `${protocol}://${hostname}:${port}${
normalizedAssetPrefix ? `/${normalizedAssetPrefix}` : ''
}`
if (normalizedAssetPrefix.startsWith('http')) {
url = `${protocol}://${normalizedAssetPrefix.split('://')[1]}`
}
return url
}
import { useCallback, useContext, useEffect, useRef } from 'react' import { useCallback, useContext, useEffect, useRef } from 'react'
import { GlobalLayoutRouterContext } from '../../../../../shared/lib/app-router-context' import { GlobalLayoutRouterContext } from '../../../../../shared/lib/app-router-context'
import { getSocketProtocol } from './get-socket-protocol' import { getSocketUrl } from './get-socket-url'
export function useWebsocket( export function useWebsocket(assetPrefix: string) {
assetPrefix: string,
shouldSubscribe: boolean = true
) {
const webSocketRef = useRef<WebSocket>() const webSocketRef = useRef<WebSocket>()
useEffect(() => { useEffect(() => {
if (webSocketRef.current || !shouldSubscribe) { if (webSocketRef.current) {
return return
} }
const { hostname, port } = window.location const url = getSocketUrl(assetPrefix)
const protocol = getSocketProtocol(assetPrefix)
const normalizedAssetPrefix = assetPrefix.replace(/^\/+/, '')
let url = `${protocol}://${hostname}:${port}${
normalizedAssetPrefix ? `/${normalizedAssetPrefix}` : ''
}`
if (normalizedAssetPrefix.startsWith('http')) {
url = `${protocol}://${normalizedAssetPrefix.split('://')[1]}`
}
webSocketRef.current = new window.WebSocket(`${url}/_next/webpack-hmr`) webSocketRef.current = new window.WebSocket(`${url}/_next/webpack-hmr`)
}, [assetPrefix, shouldSubscribe]) }, [assetPrefix])
return webSocketRef return webSocketRef
} }
......
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