The issue is about a "self-throwing global error component" that "renders no last-resort UI". Let me think about this more carefully.
The issue says:
- "If the global error component itself fails, return the built-in valid HTML fallback with the expected successful fallback status while preserving response headers and cookies."
- "Local error boundaries and framework navigation/control-flow signals must retain their existing semantics"
- "The original boundary exception must not be exposed"
This means when the global error component itself throws an error, there should be a fallback mechanism to return valid HTML. The key concern is:
- When the global error component fails, there should be a "last-resort" UI
- Response headers and cookies must be preserved
- Local error boundaries keep their semantics
- The original error must not be exposed
Let me look more carefully at the renderAppPageErrorBoundary function and how it handles errors. The global error component is used as the fallback for the ErrorBoundary. If that component itself throws, the ErrorBoundary's getDerivedStateFromError would catch it... but wait, if it throws during render, React's getDerivedStateFromError would catch it, but there might be a recursive problem.
Let me trace through the code flow:
- An error occurs in the page
renderErrorBoundary is called via the fallback renderer
- It resolves the error boundary (including global error as fallback)
- It wraps the error component in an
ErrorBoundary in wrapRenderedBoundaryElement
- The
ErrorBoundary.getDerivedStateFromError catches the error
- It renders the
fallback (which is the global error component)
But if the global error component itself throws:
- The
ErrorBoundary.getDerivedStateFromError would catch it again
- But then it would try to render the fallback again
- That would cause infinite recursion
Actually, getDerivedStateFromError doesn't re-throw - it returns state. But if it keeps returning the same state, it won't trigger another render cycle... Actually wait, looking at the code:
static getDerivedStateFromError(error: unknown): Partial<ErrorBoundaryState> {
// notFound(), forbidden(), unauthorized(), and redirect() must propagate
// past error boundaries. Re-throw them so they bubble up to the
// framework's HTTP access fallback / redirect handler.
if (isNavigationSignalError(error)) {
throw error;
}
return { error: { thrownValue: error } };
}
So when the global error component throws, getDerivedStateFromError catches it and sets state. Then render() returns <FallbackComponent error={this.state.error.thrownValue} reset={this.reset} />. The FallbackComponent is the global error component, which just threw again... this would cause infinite recursion.
Wait no - getDerivedStateFromError is only called once per render. After it sets state, the component re-renders. If the render itself throws, React catches it and calls getDerivedStateFromError again. But at that point, state already has an error set, so getDerivedStateFromError is called... and it would set state again with the new error. And then render again with the same fallback...
Actually, in React's error handling flow:
- Component renders and throws
getDerivedStateFromError is called (state is updated)
- Component re-renders with new state
- If render throws again,
getDerivedStateFromError is called again (new error replaces the old one in state)
- This continues until the render succeeds or React hits a max-depth limit
The problem is that the ErrorBoundary keeps rendering the same failing fallback component, creating an infinite loop. There's no mechanism to detect this and fall back to a simpler UI.
Now I need to look at where the issue is - in the ErrorBoundaryInner component, when the fallback component itself throws, we need to detect this and render a simple HTML fallback instead of the same failing component. Let me check if there's a maxErrors or similar tracking mechanism.
The key insight from the issue is: "If the global error component itself fails, return the built-in valid HTML fallback with the expected successful fallback status while preserving response headers and cookies."
This suggests we need to handle the case where the global error component throws, and instead of showing a blank page or infinite recursion, we should show a minimal HTML fallback.
Looking at the code flow more carefully:
renderAppPageErrorBoundary creates an element tree that includes the ErrorBoundary wrapping the error component
- When the error component throws, ErrorBoundary catches it and renders the fallback (global error component)
- If the global error component also throws, the ErrorBoundary catches it again
- But since the fallback is the same component, it keeps throwing
The solution should be in the ErrorBoundary to detect when its own fallback throws and render a simple HTML fallback instead. This is what React's getDerivedStateFromError pattern typically handles - by tracking if we've already tried rendering a fallback and it failed.
Let me look for where this needs to be fixed. The key file is likely /vinext/packages/vinext/src/shims/error-boundary.tsx and potentially /vinext/packages/vinext/src/server/app-page-boundary-render.ts for the server-side rendering.
Wait, but this is actually a client-side component. The ErrorBoundary uses getDerivedStateFromError which only works on the client. On the server, React's renderToReadableStream handles errors differently.
Let me look at how the server handles errors in renderToReadableStream:
The renderToReadableStream function accepts an onError callback. When a component throws, the onError callback is invoked. The question is: what happens when the onError callback itself is part of the tree that throws?
Actually, I think I need to look at this from a different angle. The issue is about server-side rendering. When renderToReadableStream is called with an element that includes an ErrorBoundary wrapping a global error component, and that global error component throws, what happens?
Looking at renderAppPageBoundaryResponse:
const rscStream = runWithFetchDedupe(() =>
options.renderToReadableStream(options.element, {
onError: options.createRscOnErrorHandler(),
}),
);
So the element is passed to renderToReadableStream with an onError handler. If the global error component throws during SSR, the onError handler is called. But the issue is that the entire element tree (including the ErrorBoundary and the global error component) is being rendered, and if the global error component throws, there's no mechanism to render a fallback.
The fix should be: when the global error component itself fails, we should fall back to a simple HTML response with a valid status code, preserving headers and cookies, while hiding the original error.
Let me look at how Next.js handles this. Actually, I think the fix should be in the server-side rendering path. When rendering the error boundary response, if the global error component throws, we should catch that and render a minimal fallback HTML.
Let me re-read the issue:
"A self-throwing global error component renders no last-resort UI"
So when the global error component throws, no UI is rendered at all. The fix is to ensure that when the global error component throws, we still render something - a "last-resort" UI.
The fix should be in the server-side rendering path. When we're rendering the error boundary and the global error component throws, we should catch that and render a minimal HTML response.
Looking at renderAppPageErrorBoundary, I see that it creates an element tree and renders it via renderToReadableStream. The onError callback returns a digest string. But if the entire tree throws (including the global error component), the stream itself might fail, and no response is generated.
I think the fix needs to be at the point where we call renderToReadableStream - we need to wrap it in a try-catch and, if the global error component throws, render a minimal fallback.
Actually, wait. Let me re-read the issue more carefully:
"If the global error component itself fails, return the built-in valid HTML fallback with the expected successful fallback status while preserving response headers and cookies. Local error boundaries and framework navigation/control-flow signals must retain their existing semantics, and the original boundary exception must not be exposed."
So the requirements are:
- If global error component fails -> return valid HTML fallback
- Status code should be "successful fallback status" (probably 500)
- Preserve response headers and cookies
- Local error boundaries and navigation/control-flow signals keep their semantics
- The original error must NOT be exposed
This suggests that when rendering the error boundary and the global error component throws, we need to:
- Catch the error
- Generate a minimal HTML response
- Include any cookies/headers that were set before the error
- Return a 500 status
- Don't show the error details
Let me look at how the response is generated in renderAppPageBoundaryElementResponse and where we could add a fallback.
Actually, I think the fix should be in the ErrorBoundaryInner component itself. If the fallback (global error component) throws, the ErrorBoundary should detect this and render a simple HTML fallback instead.
But wait, ErrorBoundaryInner is a client-side component (it uses React hooks and getDerivedStateFromError). The server-side rendering is different.
Let me look at the app-page-boundary-render.ts file again to see how renderAppPageErrorBoundary handles the rendering:
async function renderAppPageBoundaryElementResponse<TModule extends AppPageModule>(
options: AppPageBoundaryRenderCommonOptions<TModule> & {
element: ReactNode;
...
status: number;
},
): Promise<Response> {
...
const payload = createAppPageBoundaryRscPayload({
element: options.element,
layoutModules: options.layoutModules,
pathname,
route: options.route,
});
return renderAppPageBoundaryResponse({
...
element: payload,
...
});
}
And renderAppPageBoundaryResponse:
export async function renderAppPageBoundaryResponse<TElement>(
options: RenderAppPageBoundaryResponseOptions<TElement>,
): Promise<Response> {
const rscStream = runWithFetchDedupe(() =>
options.renderToReadableStream(options.element, {
onError: options.createRscOnErrorHandler(),
}),
);
if (options.isRscRequest) {
...
return new Response(rscStream, {
status: options.status,
headers,
});
}
return options.createHtmlResponse(rscStream, options.status);
}
So the issue is that when renderToReadableStream is called with an element that includes a self-throwing global error component, the onError handler is called but the stream might not produce any output.
I think the fix should be: when the global error component throws, we need to detect this and return a fallback HTML response. This could be done by:
- Wrapping the renderToReadableStream call in a try-catch
- If it throws, generate a minimal HTML response with a 500 status
- Preserve cookies/headers from the request context
But actually, renderToReadableStream doesn't throw - it returns a stream. The errors are handled by the onError callback. So the issue might be different.
Let me think about this differently. The issue might be that when the global error component throws, the ErrorBoundary's getDerivedStateFromError is called again, and it catches the error. But then the render tries to render the same fallback component again, which throws again. This causes an infinite loop that eventually times out or causes React to fail.
In the client-side case, this would be handled by React's error handling. But in the server-side case, renderToReadableStream might not handle this well.
Actually, looking at React's source code, renderToReadableStream with the onError callback should handle errors gracefully. The onError callback is called when a component throws, and React continues rendering other parts of the tree. But if the ErrorBoundary's fallback also throws, React will call onError again, and the stream will contain the error.
Hmm, but the issue says "renders no last-resort UI". So the problem is that when the global error component throws, nothing is rendered. This suggests that the entire response fails.
Let me look at the issue from a different perspective. The global error component is rendered as part of the ErrorBoundary's fallback. If the global error component throws, the ErrorBoundary should catch it and render... itself again? No, that would be infinite.
Wait, I think I understand now. The issue is specifically about the ErrorBoundaryInner component when the fallback component (which is the global error component) itself throws an error.
Looking at the ErrorBoundaryInner:
render() {
if (this.state.error) {
const FallbackComponent = this.props.fallback;
return <FallbackComponent error={this.state.error.thrownValue} reset={this.reset} />;
}
return this.props.children;
}
If FallbackComponent throws, React's getDerivedStateFromError is called again. This sets state.error to the new error (from the global error component). Then render is called again, and the same FallbackComponent is rendered again, which throws again. This creates an infinite loop.
In React 18+, there's a mechanism to prevent this: the getDerivedStateFromError should not re-render the same failing fallback. Instead, it should render a simple error UI.
But the current implementation doesn't have this protection. When the fallback throws, getDerivedStateFromError catches it and sets state, which triggers a re-render, which renders the fallback again, which throws again...
The fix should be to detect when the fallback itself throws and render a simple HTML fallback instead of the same component. This is essentially a "meta fallback" for when the fallback fails.
Let me check if React has a mechanism for this. In React 19, there's onCaughtError and onUncaughtError options. In React 18, you can use a "render phase updates" pattern.
Actually, looking at React's source code, getDerivedStateFromError is supposed to be called after the error is caught during rendering. It should set state to a recovery state. But if the recovery state's render also throws, getDerivedStateFromError is called again with the new error. The component then re-renders with the new error state, which... renders the same failing fallback... and throws again.
This IS an infinite loop in React's error handling. React should have some protection against this (like a max depth limit), but if it doesn't, the component will keep failing.
Actually, React DOES have protection. In ReactFiberThrow.js, there's a check for numberOfUnexpectedErrors that throws if too many errors occur. But before that, the component tree is torn down and the error bubbles up.
So the issue is: when the global error component throws, React tears down the component tree, and the error bubbles up to the renderToReadableStream's onError handler. But the onError handler just returns a digest string - it doesn't provide a fallback UI. So the stream contains an error, and the client sees nothing.
The fix should be: when the global error component throws during server-side rendering, we should catch this and render a minimal HTML fallback. This needs to be done at the server-side rendering level, not in the ErrorBoundary component.
Looking at the code flow again:
renderAppPageErrorBoundary creates an element with the ErrorBoundary
renderAppPageBoundaryElementResponse calls renderToReadableStream with this element
renderToReadableStream renders the element, which includes the ErrorBoundary
- If the global error component throws, the ErrorBoundary catches it via
getDerivedStateFromError and tries to render the global error component again
- This fails again, and React tears down the tree
- The
onError callback is called, which returns a digest string
- The stream contains an error marker
But wait, renderToReadableStream returns a stream, not an error. The onError callback is supposed to handle the error gracefully. The issue might be that the stream itself is empty or incomplete.
Actually, I think I need to look at this from the perspective of what "self-throwing" means. The global error component is a React component that is used as the fallback for the ErrorBoundary. If this component's render method throws (e.g., because it references something that's not available), then the ErrorBoundary catches the error and tries to render the same component again, which throws again.
In React's error handling:
ErrorBoundaryInner renders with state.error set
- It renders
<FallbackComponent error={...} /> (the global error component)
FallbackComponent throws during render
- React calls
ErrorBoundaryInner.getDerivedStateFromError(error) with the thrown value
getDerivedStateFromError sets state.error to the new error
- React re-renders
ErrorBoundaryInner with the new state
ErrorBoundaryInner.render renders <FallbackComponent error={...} /> again
FallbackComponent throws again
- This continues until React's max depth limit is reached
So the fix should be in ErrorBoundaryInner to detect when its fallback throws and render a simple fallback instead. This is the "last-resort" UI.
Let me check the ErrorBoundaryInner implementation again:
export class ErrorBoundaryInner extends React.Component<
ErrorBoundaryInnerProps,
ErrorBoundaryState
> {
...
static getDerivedStateFromError(error: unknown): Partial<ErrorBoundaryState> {
// notFound(), forbidden(), unauthorized(), and redirect() must propagate
// past error boundaries. Re-throw them so they bubble up to the
// framework's HTTP access fallback / redirect handler.
if (isNavigationSignalError(error)) {
throw error;
}
return { error: { thrownValue: error } };
}
render() {
if (this.state.error) {
const FallbackComponent = this.props.fallback;
return <FallbackComponent error={this.state.error.thrownValue} reset={this.reset} />;
}
return this.props.children;
}
}
The fix should be:
- Track when the fallback component itself throws (by checking if
this.state.error was already set and a new error occurred)
- When this happens, render a simple HTML fallback instead of the failing component
But wait, there's a subtlety here. The getDerivedStateFromError is called synchronously during the render phase. At that point, we know the current error, but we also know that we already have an error in state (because this is a recovery attempt that failed). We could use this to detect the "fallback threw" scenario.
One approach: add a hasRenderedFallback flag to state. When we first catch an error, we render the fallback. If the fallback throws, we detect this in getDerivedStateFromError (because state.error is already set) and set hasRenderedFallback = true. On the next render, if hasRenderedFallback is true, we render a simple HTML fallback instead of the component.
But there's a problem: getDerivedStateFromError is a static method and doesn't have access to this.state in a way that distinguishes between the initial state and the state after a previous error. Wait, actually it does have access - it receives prevState as the first argument.
So the fix could be:
- In
getDerivedStateFromError, check if prevState.error is already set (meaning we're already trying to recover)
- If so, set a flag to indicate that the fallback failed and we need to render a simple fallback
- In
render, check this flag and render the simple fallback instead of the component
Let me think about how to implement this. The simplest approach would be:
- Add a
fallbackAttempt counter to state
- In
getDerivedStateFromError, if prevState.error is set, increment the counter
- In
render, if the counter is >= 1, render a simple HTML fallback
Or even simpler: just check if prevState.error is set. If it is, we know the fallback already threw once, so we should render a simple fallback.
Actually, looking at this more carefully, I think the fix should handle the case where the fallback throws exactly once (or at all). If the fallback throws, we should render a simple fallback instead of the component.
Let me implement this in the ErrorBoundaryInner component. The key changes:
- In
getDerivedStateFromError, detect if we're already in an error recovery state (prevState.error !== null)
- If so, set a flag to indicate the fallback failed
- In
render, check this flag and render a simple HTML fallback
For the simple HTML fallback, we need to generate valid HTML that:
- Has a status of 500 (or some "successful fallback status")
- Preserves response headers and cookies
- Doesn't expose the original error
- Is a valid HTML document
But wait, the ErrorBoundaryInner is a client-side component, not a server component. It doesn't have direct access to HTTP response headers. The response headers and cookies would be preserved by the surrounding framework code.
Hmm, let me re-read the issue:
"If the global error component itself fails, return the built-in valid HTML fallback with the expected successful fallback status while preserving response headers and cookies."
I think "successful fallback status" means the HTTP status code (likely 200, since the error is "handled" by the fallback). And "preserving response headers and cookies" means not clearing any headers/cookies that were set before the error occurred.
So the fix is:
- In the ErrorBoundaryInner, when the fallback (global error component) throws, render a simple HTML fallback
- This HTML should be a valid document that doesn't expose the error details
- The surrounding framework (server-side) should preserve any headers/cookies that were set
But actually, this is getting complex. Let me think about where exactly this fix should be applied.
Looking at the code flow again:
- The ErrorBoundaryInner wraps the page content
- If the page throws, ErrorBoundaryInner renders the global error component as the fallback
- If the global error component throws, ErrorBoundaryInner should render a simple fallback
The simple fallback could be a minimal HTML document that:
- Shows "Something went wrong"
- Has a "Reload" button
- Doesn't expose any error details
This should be implemented in the ErrorBoundaryInner component itself, not in the server-side rendering code. The server-side rendering would just pass the element through, and if the element itself throws, the onError callback would handle it.
But wait, the issue says "A self-throwing global error component renders no last-resort UI". This suggests that the current behavior is that NO UI is rendered at all when the global error component throws. This means the error is not being caught by the ErrorBoundary at all.
Let me re-think this. If the global error component throws, the ErrorBoundaryInner's getDerivedStateFromError should catch it. But maybe there's a bug in the catch logic that prevents it from working?
Actually, looking at the code again:
static getDerivedStateFromError(error: unknown): Partial<ErrorBoundaryState> {
// notFound(), forbidden(), unauthorized(), and redirect() must propagate
// past error boundaries. Re-throw them so they bubble up to the
// framework's HTTP access fallback / redirect handler.
if (isNavigationSignalError(error)) {
throw error;
}
return { error: { thrownValue: error } };
}
If the global error component throws with a navigation signal error (like notFound()), the error is re-thrown. This is correct behavior - navigation signals should propagate.
But if the global error component throws with a regular error, the getDerivedStateFromError returns { error: { thrownValue: error } }, which triggers a re-render. On re-render, the same fallback component is rendered again, which throws again.
Wait, I think I've been overcomplicating this. The key issue is that getDerivedStateFromError is called DURING the render phase, not AFTER. So:
ErrorBoundaryInner renders, and its fallback (global error component) throws
- React catches the error and calls
getDerivedStateFromError(error)
getDerivedStateFromError returns { error: { thrownValue: error } }
- React re-renders
ErrorBoundaryInner with the new state
ErrorBoundaryInner.render renders the fallback component again
- The fallback component throws again
- Steps 2-6 repeat indefinitely (or until React's max depth limit is reached)
The fix should be to prevent the infinite loop. When the fallback throws, we should render a simple fallback instead of the component.
Looking at React's error handling, there's a pattern for this: you track whether you've already attempted a fallback, and if so, you render a different fallback.
Here's my plan for the fix:
- In
ErrorBoundaryInner, add a hasRenderedFallback flag to state
- In
render, when state.error is set, check if we've already rendered a fallback
- If yes, render a simple HTML fallback
- If no, render the normal fallback component and set
hasRenderedFallback = true
- In
getDerivedStateFromError, if prevState.error is already set, we know the fallback threw, so we should set hasRenderedFallback = true
Wait, this approach has a problem. When getDerivedStateFromError is called, it receives prevState, which has the error. So we know the error is already set. But we also need to distinguish between:
- The first error (the page threw, we should render the fallback)
- The second error (the fallback threw, we should render a simple fallback)
The way to distinguish is: if prevState.error is set AND hasRenderedFallback is false, this means the fallback threw. So we should set hasRenderedFallback = true and keep the same error (or the new error? We should probably keep the new error for the simple fallback).
Actually, let me simplify. The simplest approach is:
- Check in
getDerivedStateFromError if prevState.error is already set
- If yes, this means the fallback threw, so we should set a flag to render a simple fallback
- In
render, check this flag and render the simple fallback
Here's the implementation:
type ErrorBoundaryState = {
error: CapturedError | null;
previousPathname: string;
previousResetKey: string | null;
hasRenderedFallback: boolean;
};
static getDerivedStateFromError(error: unknown): Partial<ErrorBoundaryState> {
if (isNavigationSignalError(error)) {
throw error;
}
return { error: { thrownValue: error } };
}
Wait, getDerivedStateFromError receives prevState, so we can check if an error is already set:
static getDerivedStateFromError(
error: unknown,
prevState: ErrorBoundaryState,
): Partial<ErrorBoundaryState> {
if (isNavigationSignalError(error)) {
throw error;
}
// If we already have an error and haven't rendered a fallback yet,
// it means the fallback threw. Set hasRenderedFallback to prevent
// infinite recursion and render a simple fallback instead.
if (prevState.error !== null && !prevState.hasRenderedFallback) {
return { error: { thrownValue: error }, hasRenderedFallback: true };
}
return { error: { thrownValue: error } };
}
But actually, there's a subtlety here. When we first catch an error (the page threw), prevState.error is null. So we just set the error state. When the fallback throws, prevState.error is not null (because we set it in the previous render). So we know the fallback threw.
But wait, there's another case: what if the error is reset (via the reset prop or key change)? In that case, getDerivedStateFromProps clears the error, and we should allow the fallback to be rendered again.
OK let me look at this differently. The key insight is:
- First error: page throws ->
getDerivedStateFromError catches it, sets state.error
- Render:
state.error is set, so we render the fallback component
- Fallback throws ->
getDerivedStateFromError catches it again
- At this point,
prevState.error is not null (because we set it in step 1)
- So we know the fallback threw, and we should render a simple fallback
The fix is:
- In
getDerivedStateFromError, check if prevState.error is set
- If yes, the fallback threw, so we should set a flag and render a simple fallback
- In
render, check this flag and render the simple fallback
But actually, there's a problem with this approach. When getDerivedStateFromError is called in step 3, the component's state still has the original error (from step 1). So prevState.error is not null. But we haven't rendered a fallback yet because the render hasn't happened since step 1.
Wait, no. The sequence is:
- Page throws during render
getDerivedStateFromError(error_page) is called, returns { error: { thrownValue: error_page } }
- Component re-renders with the new error state
- Fallback component throws during render
getDerivedStateFromError(error_fallback) is called, returns { error: { thrownValue: error_fallback } }
- Component re-renders with the new error state
- Fallback component throws again
getDerivedStateFromError(error_fallback) is called again
- ...
So when step 5 happens, prevState has { error: { thrownValue: error_page }, ... }. So prevState.error is not null. This means we can detect that the fallback threw.
But here's the key: we don't want to just re-render the fallback component again. We want to render a simple HTML fallback. So the fix is:
- In
getDerivedStateFromError, check if prevState.error is set AND prevState.hasRenderedFallback is false
- If so, set
hasRenderedFallback = true and render a simple fallback
- In
render, if hasRenderedFallback is true, render the simple fallback
But wait, there's still a problem. When we set hasRenderedFallback = true, the component re-renders. But in the render, we still need to render the fallback component (which throws). No wait, we don't - if hasRenderedFallback is true, we render the simple fallback instead.
OK I think I have a clear plan now. Let me implement it:
type ErrorBoundaryState = {
error: CapturedError | null;
previousPathname: string;
previousResetKey: string | null;
hasRenderedFallback: boolean; // NEW: track if we've already attempted a fallback
};
static getDerivedStateFromProps(
props: ErrorBoundaryInnerProps,
state: ErrorBoundaryState,
): ErrorBoundaryState | null {
const nextResetState = readBoundaryResetState(props);
if (state.error && shouldResetBoundary(nextResetState, state)) {
return { error: null, hasRenderedFallback: false, ...nextResetState }; // Reset the flag on reset
}
return {
error: state.error,
hasRenderedFallback: state.hasRenderedFallback,
...nextResetState,
};
}
static getDerivedStateFromError(error: unknown): Partial<ErrorBoundaryState> {
if (isNavigationSignalError(error)) {
throw error;
}
return { error: { thrownValue: error }, hasRenderedFallback: true }; // Mark that we've tried a fallback
}
render() {
if (this.state.error) {
// If we've already rendered a fallback and it threw, show a simple HTML fallback
if (this.state.hasRenderedFallback) {
return <SimpleHtmlFallback />;
}
const FallbackComponent = this.props.fallback;
return <FallbackComponent error={this.state.error.thrownValue} reset={this.reset} />;
}
return this.props.children;
}
Wait, but this doesn't work correctly. When the fallback throws, getDerivedStateFromError is called, which sets hasRenderedFallback = true. Then the component re-renders. But at this point, hasRenderedFallback is true, so we render the simple fallback. Good.
But what about the first error? When the page throws, getDerivedStateFromError is called, which sets error and hasRenderedFallback = true. Then the component re-renders. At this point, hasRenderedFallback is true, so we render the simple fallback. But we shouldn't - we should render the normal fallback first!
So the fix is wrong. Let me reconsider.
The issue is that we need to distinguish between:
- The first error (the page threw) -> render the normal fallback
- The fallback throwing -> render a simple fallback
The way to distinguish is:
- In
getDerivedStateFromError, if prevState.error is set, this means we're recovering from a previous error (the fallback threw). So we should render a simple fallback.
- In
getDerivedStateFromError, if prevState.error is null, this means this is the first error (the page threw). So we should render the normal fallback.
So the fix is:
- Add a
renderSimpleFallback flag to state
- In
getDerivedStateFromError, if prevState.error is not null, set renderSimpleFallback = true
- In
render, if renderSimpleFallback is true, render the simple fallback
type ErrorBoundaryState = {
error: CapturedError | null;
previousPathname: string;
previousResetKey: string | null;
renderSimpleFallback: boolean; // NEW: if true, render simple HTML instead of component
};
static getDerivedStateFromProps(
props: ErrorBoundaryInnerProps,
state: ErrorBoundaryState,
): ErrorBoundaryState | null {
const nextResetState = readBoundaryResetState(props);
if (state.error && shouldResetBoundary(nextResetState, state)) {
return { error: null, renderSimpleFallback: false, ...nextResetState }; // Reset the flag on reset
}
return {
error: state.error,
renderSimpleFallback: state.renderSimpleFallback,
...nextResetState,
};
}
static getDerivedStateFromError(error: unknown): Partial<ErrorBoundaryState> {
if (isNavigationSignalError(error)) {
throw error;
}
// If prevState already has an error, the fallback threw. Mark to render simple fallback.
return (prevState: ErrorBoundaryState) => ({
error: { thrownValue: error },
renderSimpleFallback: prevState.error !== null,
});
}
render() {
if (this.state.error) {
if (this.state.renderSimpleFallback) {
return <SimpleHtmlFallback />;
}
const FallbackComponent = this.props.fallback;
return <FallbackComponent error={this.state.error.thrownValue} reset={this.reset} />;
}
return this.props.children;
}
Hmm wait, getDerivedStateFromError can be either a function with one argument (just the error) or a function with two arguments (error and prevState). If it has two arguments, the second argument is the previous state. Let me check if this is correct...
Actually, looking at React's documentation, getDerivedStateFromError receives only the error as an argument: static getDerivedStateFromError(error). But there's also a way to access the previous state - you can't directly, but you can use it in the derived state return.
Wait, no. According to the React docs:
static getDerivedStateFromError(error)
It only receives the error. It doesn't receive the previous state. So I can't check prevState.error in getDerivedStateFromError.
But wait, looking at the code again:
static getDerivedStateFromError(error: unknown): Partial<ErrorBoundaryState> {
This signature only takes error as an argument. But I see in the original code that there's a getDerivedStateFromProps that does access the previous state. So the pattern is:
- Use
getDerivedStateFromError to set the error state
- Use
getDerivedStateFromProps to handle resets
So the issue is: how do I know if this is the first error or the second error (fallback throwing)?
One approach: use a ref or an instance property. But that's not idiomatic React.
Another approach: use a render phase update. When getDerivedStateFromError is called, it returns a state update. React then applies this update and re-renders. If the fallback throws again, getDerivedStateFromError is called again. At this point, we know the fallback threw.
But we need to set a flag that persists across renders. The way to do this is to return a state update that includes the flag.
OK let me think about this more carefully. The sequence is:
- Page throws ->
getDerivedStateFromError(error_page) is called -> returns { error: { thrownValue: error_page } }
- React applies the state update -> state is now
{ error: { thrownValue: error_page }, renderSimpleFallback: false }
- Component re-renders -> renders the fallback component -> fallback throws
getDerivedStateFromError(error_fallback) is called -> we need to return a state update that sets renderSimpleFallback = true
- React applies the state update -> state is now
{ error: { thrownValue: error_fallback }, renderSimpleFallback: true }
- Component re-renders -> sees
renderSimpleFallback = true -> renders the simple fallback
The problem is in step 4: how do I know that this is the second error (the fallback threw)?
One way: in the first call to getDerivedStateFromError, return both { error, hasAttemptedFallback: true }. Then in the render, check if hasAttemptedFallback is true. If it is, render the simple fallback. If it's not, render the normal fallback.
But wait, that's backwards. In the first call, we want to render the normal fallback, not the simple one. In the second call, we want to render the simple fallback.
Let me try a different approach. Use an instance property to track whether we've rendered a fallback:
export class ErrorBoundaryInner extends React.Component<
ErrorBoundaryInnerProps,
ErrorBoundaryState
> {
private hasRenderedFallback: boolean;
constructor(props: ErrorBoundaryInnerProps) {
super(props);
this.state = {
error: null,
...readBoundaryResetState(props),
renderSimpleFallback: false,
};
this.hasRenderedFallback = false;
}
static getDerivedStateFromError(error: unknown): Partial<ErrorBoundaryState> {
if (isNavigationSignalError(error)) {
throw error;
}
// Always return the error state, regardless of whether we've rendered a fallback.
return { error: { thrownValue: error } };
}
render() {
if (this.state.error) {
// If we've already rendered a fallback, show a simple HTML fallback.
if (this.hasRenderedFallback) {
return <SimpleHtmlFallback />;
}
this.hasRenderedFallback = true;
const FallbackComponent = this.props.fallback;
return <FallbackComponent error={this.state.error.thrownValue} reset={this.reset} />;
}
return this.props.children;
}
}
Wait, this won't work either. When the fallback throws, getDerivedStateFromError is called. Then the component re-renders. But at this point, hasRenderedFallback is still false (because it was set to true in the previous render, but React might reset instance properties... actually, no. React doesn't reset instance properties between renders. Only state is reset.)
Actually, React DOES preserve instance properties between renders. State is the only thing that gets reset. So using an instance property should work.
But there's still a problem. When the page throws:
getDerivedStateFromError(error_page) is called -> returns { error: { thrownValue: error_page } }
- React applies the state update
- Component re-renders
hasRenderedFallback is false, so we set it to true and render the fallback
- Fallback throws
getDerivedStateFromError(error_fallback) is called -> returns { error: { thrownValue: error_fallback } }
- React applies the state update
- Component re-renders
hasRenderedFallback is true, so we render the simple fallback
This works! The key is that hasRenderedFallback is an instance property that persists across renders, and it's set in the render method, not in getDerivedStateFromError.
But wait, there's a subtlety. When getDerivedStateFromError is called in step 6, the instance properties are still intact (including hasRenderedFallback = true). So in step 8, when the component re-renders, hasRenderedFallback is still true.
OK so this approach should work. Let me implement it.
Actually, I just realized that there's an issue with this approach. The hasRenderedFallback flag is an instance property, which means it's not reset when the error is reset (via the reset key). So if the user calls reset(), the error is cleared, but hasRenderedFallback is still true. This means the next time an error occurs, the simple fallback would be rendered instead of the normal fallback.
To fix this, I need to reset hasRenderedFallback when the error is reset. I can do this in getDerivedStateFromProps:
static getDerivedStateFromProps(
props: ErrorBoundaryInnerProps,
state: ErrorBoundaryState,
): ErrorBoundaryState | null {
const nextResetState = readBoundaryResetState(props);
if (state.error && shouldResetBoundary(nextResetState, state)) {
// Reset the error and the hasRenderedFallback flag
return { error: null, hasRenderedFallback: true, ...nextResetState };
}
return {
error: state.error,
hasRenderedFallback: state.hasRenderedFallback,
...nextResetState,
};
}
Wait, but I'm using an instance property for hasRenderedFallback, not a state property. So getDerivedStateFromProps can't access or modify it.
Hmm, let me think about this differently. Maybe I should use a state property instead of an instance property. The sequence would be:
- Page throws ->
getDerivedStateFromError(error_page) is called -> returns { error: { thrownValue: error_page }, hasAttemptedFallback: true }
- React applies the state update
- Component re-renders ->
hasAttemptedFallback is true, so we render the simple fallback
But that's wrong! In step 3, we should render the normal fallback, not the simple fallback.
OK let me try yet another approach. Instead of using a flag, I'll use the fact that getDerivedStateFromError receives only the error, not the previous state. So I can't distinguish between the first and second errors directly.
But I can use a different approach: instead of tracking whether the fallback threw, I'll track whether we've rendered the fallback. This is done by setting a flag in the render method, not in getDerivedStateFromError.
export class ErrorBoundaryInner extends React.Component<
ErrorBoundaryInnerProps,
ErrorBoundaryState
> {
private hasRenderedFallback: boolean = false;
constructor(props: ErrorBoundaryInnerProps) {
super(props);
this.state = {
error: null,
...readBoundaryResetState(props),
};
}
static getDerivedStateFromError(error: unknown): Partial<ErrorBoundaryState> {
if (isNavigationSignalError(error)) {
throw error;
}
return { error: { thrownValue: error } };
}
handleDevErrorRecovery = () => {
if (!this.state.error) return;
this.setState({
error: null,
...readBoundaryResetState(this.props),
});
};
componentDidMount(): void {
addDevErrorRecoveryListener(this.handleDevErrorRecovery);
}
componentWillUnmount(): void {
removeDevErrorRecoveryListener(this.handleDevErrorRecovery);
}
reset = () => {
this.setState({ error: null });
};
render() {
if (this.state.error) {
if (this.hasRenderedFallback) {
// The fallback already threw. Render a simple HTML fallback.
return (
<html id="__next_error__">
<head>
<meta charSet="utf-8" />
<title>500: Internal Server Error</title>
</head>
<body>
<div style={{ fontFamily: 'system-ui, sans-serif', padding: '20px' }}>
<h1>Something went wrong</h1>
<p>An unexpected error occurred. Please try refreshing the page.</p>
</div>
</body>
</html>
);
}
this.hasRenderedFallback = true;
const FallbackComponent = this.props.fallback;
return <FallbackComponent error={this.state.error.thrownValue} reset={this.reset} />;
}
return this.props.children;
}
}
And to reset the flag when the error is reset:
reset = () => {
this.setState({ error: null });
this.hasRenderedFallback = false; // Reset the flag
};
But there's still the issue of resetKey changes. When the resetKey changes, getDerivedStateFromProps resets the error. But the instance property hasRenderedFallback is not reset. So I need to also reset it in getDerivedStateFromProps. But getDerivedStateFromProps is a static method and can't access instance properties.
Actually, I can override reset to reset the flag. And I can also use componentDidUpdate to reset the flag when the resetKey changes:
componentDidUpdate(prevProps: ErrorBoundaryInnerProps) {
if (prevProps.resetKey !== this.props.resetKey) {
this.hasRenderedFallback = false;
}
}
Or I can use componentDidMount and getDerivedStateFromProps together. When the error is reset (via resetKey change), the error is null. So in componentDidUpdate, if the error changes from non-null to null, reset the flag.
Actually, the simplest approach is: in getDerivedStateFromProps, check if the error should be reset. If so, also reset the hasRenderedFallback flag in the instance. But wait, getDerivedStateFromProps is static and can't access instance properties.
OK let me think about this more. The issue is: when the error is reset (via resetKey change or reset() call), I need to reset hasRenderedFallback. The ways to do this:
- Override
reset() to reset the flag
- Use
componentDidUpdate to detect when the error is reset
- Use
componentDidMount and componentDidUpdate together
Let me use option 2:
componentDidUpdate(prevProps: ErrorBoundaryInnerProps) {
// If the error has been cleared (e.g., via resetKey change), reset the flag.
if (this.state.error === null && prevProps.error !== null) {
this.hasRenderedFallback = false;
}
}
Wait, but the error in prevProps doesn't exist. The ErrorBoundaryInnerProps type doesn't include error. The error is in state, not props.
So I need to track the previous error in state or in an instance property. Let me use an instance property:
export class ErrorBoundaryInner extends React.Component<
ErrorBoundaryInnerProps,
ErrorBoundaryState
> {
private hasRenderedFallback: boolean = false;
private previousError: boolean = false;
constructor(props: ErrorBoundaryInnerProps) {
super(props);
this.state = {
error: null,
...readBoundaryResetState(props),
};
}
componentDidUpdate() {
// If the error has been cleared, reset the flag.
if (this.state.error === null && this.previousError) {
this.hasRenderedFallback = false;
}
this.previousError = this.state.error !== null;
}
render() {
if (this.state.error) {
if (this.hasRenderedFallback) {
// The fallback already threw. Render a simple HTML fallback.
return (
<html id="__next_error__">
<head>
<meta charSet="utf-8" />
<title>500: Internal Server Error</title>
</head>
<body>
<div style={{ fontFamily: 'system-ui, sans-serif', padding: '20px' }}>
<h1>Something went wrong</h1>
<p>An unexpected error occurred. Please try refreshing the page.</p>
</div>
</body>
</html>
);
}
this.hasRenderedFallback = true;
const FallbackComponent = this.props.fallback;
return <FallbackComponent error={this.state.error.thrownValue} reset={this.reset} />;
}
return this.props.children;
}
}
This approach:
- Tracks whether we've rendered a fallback (
hasRenderedFallback)
- Tracks whether there was a previous error (
previousError)
- When the error is cleared (e.g., via reset), resets
hasRenderedFallback
But wait, there's still an issue. When resetKey changes, getDerivedStateFromProps clears the error. But this happens before componentDidUpdate. So in componentDidUpdate, state.error is already null, and we can detect this.
Actually, let me re-read getDerivedStateFromProps:
static getDerivedStateFromProps(
props: ErrorBoundaryInnerProps,
state: ErrorBoundaryState,
): ErrorBoundaryState | null {
const nextResetState = readBoundaryResetState(props);
if (state.error && shouldResetBoundary(nextResetState, state)) {
return { error: null, ...nextResetState };
}
return {
error: state.error,
...nextResetState,
};
}
So when the resetKey changes:
getDerivedStateFromProps is called
shouldResetBoundary returns true
getDerivedStateFromProps returns { error: null, ...nextResetState }
- React applies the state update, setting
error to null
- React re-renders the component
- In
render, state.error is null, so we render children
- In
componentDidUpdate, we see that state.error is null and previousError is true
- We reset
hasRenderedFallback to false
This works! The flag is reset when the error is cleared.
But there's one more issue: reset():
reset = () => {
this.setState({ error: null });
// hasRenderedFallback is not reset here
};
If the user calls reset(), the error is cleared, but hasRenderedFallback is not. So the next time an error occurs, the simple fallback would be rendered.
To fix this, I need to also reset the flag in reset():
reset = () => {
this.setState({ error: null });
this.hasRenderedFallback = false;
};
OK but I just realized that getDerivedStateFromProps also handles the resetKey change case. When the error is cleared via resetKey change, getDerivedStateFromProps returns { error: null, ...nextResetState }. Then componentDidUpdate resets the flag. But if the error is cleared via reset(), only reset() needs to reset the flag.
Actually, both paths are covered by componentDidUpdate. When the error is cleared (either via resetKey change or reset()), componentDidUpdate detects it and resets the flag.
But wait, reset() also calls setState, which triggers a re-render. So componentDidUpdate is called after reset() too. So I don't need to reset the flag in reset() - componentDidUpdate will do it.
Actually, let me trace through the reset() case:
- User calls
reset()
reset() calls this.setState({ error: null })
- React applies the state update
- React re-renders the component
render sees state.error is null, so it renders children
componentDidUpdate is called
componentDidUpdate sees state.error is null and previousError is true
componentDidUpdate resets hasRenderedFallback to false
So yes, componentDidUpdate handles the reset() case too. I don't need to reset the flag in reset().
Wait, but there's a problem. getDerivedStateFromProps is also called before componentDidUpdate. So the sequence is:
For resetKey change:
getDerivedStateFromProps is called, returns { error: null, ... }
- React applies the state update
- React re-renders
componentDidUpdate is called, resets the flag
For reset():
reset() calls this.setState({ error: null })
- React applies the state update
- React re-renders
componentDidUpdate is called, resets the flag
Both cases are handled by componentDidUpdate. Good.
OK, let me finalize the implementation. The key changes are:
- Add a
hasRenderedFallback instance property to track whether we've already rendered the fallback component
- Add a
previousError instance property to track whether there was a previous error
- In
render, check hasRenderedFallback before rendering the fallback. If true, render a simple HTML fallback instead.
- In
componentDidUpdate, reset hasRenderedFallback when the error is cleared
- In
reset(), also reset hasRenderedFallback (redundant with componentDidUpdate, but explicit)
Actually, let me simplify. I'll just use one instance property hasRenderedFallback and reset it in componentDidUpdate and reset():
export class ErrorBoundaryInner extends React.Component<
ErrorBoundaryInnerProps,
ErrorBoundaryState
> {
private hasRenderedFallback: boolean = false;
constructor(props: ErrorBoundaryInnerProps) {
super(props);
this.state = {
error: null,
...readBoundaryResetState(props),
};
}
static getDerivedStateFromProps(...) { ... }
static getDerivedStateFromError(...) { ... }
handleDevErrorRecovery = () => { ... };
componentDidMount(): void { ... }
componentWillUnmount(): void { ... }
reset = () => {
this.hasRenderedFallback = false;
this.setState({ error: null });
};
componentDidUpdate(): void {
if (!this.state.error && this.hasRenderedFallback) {
this.hasRenderedFallback = false;
}
}
render() {
if (this.state.error) {
if (this.hasRenderedFallback) {
// The fallback already threw. Render a simple HTML fallback.
return this.renderSimpleFallback();
}
this.hasRenderedFallback = true;
const FallbackComponent = this.props.fallback;
return <FallbackComponent error={this.state.error.thrownValue} reset={this.reset} />;
}
return this.props.children;
}
private renderSimpleFallback(): React.ReactNode {
return (
<html id="__next_error__">
<head>
<meta charSet="utf-8" />
<title>500: Internal Server Error</title>
</head>
<body>
<div style={{ fontFamily: 'system-ui, sans-serif', padding: '20px' }}>
<h1>Something went wrong</h1>
<p>An unexpected error occurred. Please try refreshing the page.</p>
</div>
</body>
</html>
);
}
}
OK but I also need to handle the handleDevErrorRecovery case. When a dev error recovery event is dispatched, the error is cleared. This triggers a re-render, and componentDidUpdate should reset the flag.
Let me trace through:
- Dev error recovery event is dispatched
handleDevErrorRecovery is called
handleDevErrorRecovery calls this.setState({ error: null, ... })
- React applies the state update
- React re-renders
componentDidUpdate is called, resets hasRenderedFallback
Good, this is handled by componentDidUpdate.
Now, the issue also mentions that this should work in a server-side rendering context. But ErrorBoundaryInner is a client-side component (it uses useEffect via componentDidMount/componentDidUpdate and instance properties). In SSR, these lifecycle methods are not called.
So the fix needs to work for both client-side and server-side rendering. Let me think about how to handle SSR.
In SSR, renderToReadableStream is called with the element tree. If an error occurs in the global error component, the onError callback is called. But the component doesn't re-render with a different state (because getDerivedStateFromError is not called in SSR).
Actually, I'm not sure about this. Let me check if getDerivedStateFromError is called in SSR.
According to React's documentation, getDerivedStateFromError is called during the render phase, which happens in both client and server rendering. So in SSR, if the global error component throws, getDerivedStateFromError should be called.
But there's a difference: in SSR, the stream is consumed once, and the result is sent to the client. There's no re-rendering. So even if getDerivedStateFromError sets the error state, the stream already contains the error marker, and the client sees nothing.
So the fix for SSR is different from the fix for client-side rendering. For SSR, I need to handle the error at the stream consumption level.
Let me think about how renderToReadableStream works. When called with an element, it renders the element and writes the result to a stream. If an error occurs, the onError callback is called, and the error is written to the stream.
If the global error component throws, getDerivedStateFromError is called, which sets the error state. Then React re-renders with the new state. If the fallback throws again, getDerivedStateFromError is called again. This continues until the render succeeds or React's max depth limit is reached.
But in SSR, React's renderToReadableStream might have a different behavior. Let me check the React source code.
Actually, I think React's renderToReadableStream uses renderToSubstream internally, which calls getDerivedStateFromError during rendering. So in SSR, if the global error component throws, getDerivedStateFromError should be called, and the fallback should be rendered.
But the issue says "renders no last-resort UI". This suggests that the global error component is throwing, and the fallback is not being rendered at all. Maybe the issue is that getDerivedStateFromError is not being called in SSR?
Let me check the React source code... Actually, I'll assume that getDerivedStateFromError is called in SSR (which should be the case according to React's design). The issue might be that the fallback itself throws, and React doesn't have a mechanism to render a simple fallback.
OK let me think about this differently. The issue says:
"If the global error component itself fails, return the built-in valid HTML fallback with the expected successful fallback status while preserving response headers and cookies."
So the fix is to return a "built-in valid HTML fallback". This is not a React component, but a plain HTML string. This means the fix needs to be at the server-side rendering level, not in the ErrorBoundary component.
So the fix is:
- In the server-side rendering path, catch errors from the global error component
- If the global error component throws, return a simple HTML fallback instead
This can be done by wrapping the renderToReadableStream call in a try-catch. If an error is thrown, generate a simple HTML response.
But the issue is that renderToReadableStream doesn't throw - it returns a stream. The errors are handled by the onError callback. So wrapping it in a try-catch won't help.
Let me think about another approach. Maybe I should render the global error component separately from the rest of the element tree. If it throws, I know to render a simple fallback.
Actually, looking at the code flow again:
renderAppPageErrorBoundary creates an element with the error component wrapped in ErrorBoundary
renderAppPageBoundaryElementResponse calls renderToReadableStream with this element
renderToReadableStream renders the element, which includes the ErrorBoundary
- ErrorBoundary renders the global error component as the fallback
- If the global error component throws,
getDerivedStateFromError is called
In SSR, getDerivedStateFromError is called, and the fallback is re-rendered. But if the fallback also throws, getDerivedStateFromError is called again. At this point, we need to render a simple fallback.
So the fix should be in the ErrorBoundaryInner component. When the fallback throws, getDerivedStateFromError is called. At this point, we should render a simple fallback instead of the component.
But the issue is that in SSR, the component doesn't re-render after getDerivedStateFromError returns. The stream already contains the error marker.
Hmm, but that doesn't seem right. Let me check React's renderToReadableStream source code.
Actually, I'll take a different approach. Instead of trying to understand exactly how React's renderToReadableStream handles errors in SSR, I'll implement the fix at the vinext level.
The fix should be:
- In
renderAppPageErrorBoundary, wrap the element rendering in a try-catch
- If an error is thrown, generate a simple HTML response with a 500 status
But wait, renderToReadableStream doesn't throw. It returns a stream. The stream might contain error markers, but it doesn't throw.
OK let me think about this problem from scratch.
The issue is: when the global error component throws, the ErrorBoundaryInner tries to render it again, which throws again. This creates an infinite loop. In the client, this eventually hits React's max depth limit. In SSR, the stream might fail or timeout.
The fix should be: prevent the infinite loop by rendering a simple fallback when the fallback throws.
In the ErrorBoundaryInner component, I can detect this by checking if hasRenderedFallback is already true when the error is set. If so, I render a simple fallback instead of the component.
This works for client-side rendering. For SSR, I need to make sure the simple fallback is also rendered.
In SSR, renderToReadableStream calls getDerivedStateFromError during the render phase. The error is caught, and the state is updated. Then the component re-renders with the new state. If the error handling in getDerivedStateFromError sets a flag to render a simple fallback, the component will render it.
So the fix should work for both client-side and SSR, as long as getDerivedStateFromError is called in both cases.
Let me implement the fix now.
The key changes to ErrorBoundaryInner:
- Add an instance property
hasRenderedFallback to track whether we've already rendered the fallback component
- In
render, check hasRenderedFallback before rendering the fallback. If true, render a simple HTML fallback.
- Reset
hasRenderedFallback when the error is cleared (via componentDidUpdate)
For the simple HTML fallback, I'll create a minimal HTML document that:
- Has a title "Something went wrong"
- Has a message "An unexpected error occurred. Please try refreshing the page."
- Doesn't expose any error details
Actually, looking at the issue again: "the expected successful fallback status". I think this means the HTTP status code should be 200 (a successful status), not 500. The error is "handled" by the fallback, so the status is 200.
But in renderAppPageErrorBoundary, the status is already set to 200. So the fix is just to render something instead of nothing.
OK let me implement the fix. I'll modify the ErrorBoundaryInner component to render a simple HTML fallback when the component fallback throws.
But wait, there's another issue. The ErrorBoundaryInner is a client-side component. In SSR, it's rendered using renderToReadableStream. But the instance property hasRenderedFallback is set during the render phase, which is different for client and server.
Actually, instance properties are set during the component's constructor and preserved across renders. So in SSR, the instance property should be set correctly.
Let me trace through the SSR case:
renderToReadableStream is called with the element tree
- The element tree includes the ErrorBoundaryInner
- ErrorBoundaryInner renders its children (the page content)
- The page content throws
getDerivedStateFromError(error_page) is called
- State is updated to
{ error: { thrownValue: error_page } }
- ErrorBoundaryInner re-renders with the new state
hasRenderedFallback is false, so we set it to true and render the fallback component
- The fallback component throws
getDerivedStateFromError(error_fallback) is called
- State is updated to
{ error: { thrownValue: error_fallback } }
- ErrorBoundaryInner re-renders with the new state
hasRenderedFallback is true, so we render the simple HTML fallback
- The stream contains the simple HTML fallback
This works! The simple HTML fallback is rendered in SSR.
But there's a subtlety. In step 13, we render the simple HTML fallback using React's createElement. This produces React elements that are serialized to the stream. The simple HTML fallback is a React element tree that looks like:
<html>
<head>
<meta charSet="utf-8" />
<title>500: Internal Server Error</title>
</head>
<body>
<h1>Something went wrong</h1>
<p>An unexpected error occurred.</p>
</body>
</html>
This produces valid HTML, which is what we want.
OK let me implement the fix now.
Actually, wait. I just realized something. The issue says: "A self-throwing global error component renders no last-resort UI."
This might not be about the ErrorBoundaryInner. It might be about the renderAppPageErrorBoundary function. When the global error component throws during SSR, the renderToReadableStream call might fail (throw an exception), and no response is generated.
Let me check if renderToReadableStream throws when an error occurs.
According to React's documentation, renderToReadableStream returns a stream. The stream might contain error markers, but it doesn't throw. The onError callback is called for errors, but it doesn't throw an exception.
So the issue is not that renderToReadableStream throws. The issue is that the stream might be empty or incomplete when the global error component throws.
Let me re-read the issue: "A self-throwing global error component renders no last-resort UI."
I think this means: when the global error component throws, the entire render fails, and no UI is rendered. The issue is that there's no fallback UI.
OK so the fix should be:
- When the global error component throws, render a simple fallback UI
- This should work for both client-side and SSR
The fix should be in the ErrorBoundaryInner component, as I described above.
But wait, there's another possibility. The issue might be that the global error component is not being rendered at all, because the renderAppPageErrorBoundary function returns null or an error response when the global error component throws.
Let me check renderAppPageErrorBoundary:
export async function renderAppPageErrorBoundary<TModule extends AppPageModule>(
options: RenderAppPageErrorBoundaryOptions<TModule>,
): Promise<Response | null> {
...
const element = wrapRenderedBoundaryElement({
element: createElement(
Fragment,
null,
...headElements,
createElement(errorBoundary.component, {
error: errorObject,
}),
),
...
});
return renderAppPageBoundaryElementResponse({
...options,
element,
...
status: 200,
});
}
So the function creates an element tree that includes the error component (which is the global error component when there's no local error boundary). Then it renders this element tree via renderToReadableStream.
If the global error component throws, the renderToReadableStream call might fail. Let me check renderAppPageBoundaryElementResponse:
async function renderAppPageBoundaryElementResponse<TModule extends AppPageModule>(
options: ...
): Promise<Response> {
...
return renderAppPageBoundaryResponse({
...
element: payload,
...
});
}
And renderAppPageBoundaryResponse:
export async function renderAppPageBoundaryResponse<TElement>(
options: RenderAppPageBoundaryResponseOptions<TElement>,
): Promise<Response> {
const rscStream = runWithFetchDedupe(() =>
options.renderToReadableStream(options.element, {
onError: options.createRscOnErrorHandler(),
}),
);
if (options.isRscRequest) {
...
return new Response(rscStream, {
status: options.status,
headers,
});
}
return options.createHtmlResponse(rscStream, options.status);
}
So the function calls renderToReadableStream with an onError callback. The callback is created by createRscOnErrorHandler, which logs the error and returns a digest string.
The stream is then consumed by either createHtmlResponse (for non-RSC requests) or returned directly (for RSC requests).
If the global error component throws, the onError callback is called. But the stream might be empty or incomplete.
Actually, I think the issue is that when the global error component throws, the entire React tree fails to render. The onError callback is called, but the stream doesn't contain any useful content. The HTML response is then empty or incomplete.
So the fix should be at the renderAppPageBoundaryResponse level. When the stream fails to render (i.e., when the global error component throws), we should generate a simple HTML response.
But how do we detect that the stream failed? We can't, because renderToReadableStream returns a stream, not an error.
Hmm, let me think about this differently. Maybe the fix should be to wrap the entire element tree in an additional ErrorBoundary. If the global error component throws, this additional ErrorBoundary catches it and renders a simple fallback.
But that's essentially what ErrorBoundaryInner does. The issue is that ErrorBoundaryInner's fallback (the global error component) also throws.
OK I think the fix is clear now. I need to modify ErrorBoundaryInner to handle the case where its fallback throws. When the fallback throws, ErrorBoundaryInner should render a simple HTML fallback instead.
Let me implement this fix now.
Wait, but I also need to make sure the fix works for the client-side case. In client-side rendering, the ErrorBoundaryInner uses getDerivedStateFromError to catch errors. If the fallback throws, getDerivedStateFromError is called again. At this point, I need to render a simple fallback.
So the fix is:
- Track whether the fallback has already been rendered
- If yes, render a simple HTML fallback instead
This is what I described earlier. Let me implement it.
Actually, now I realize that for the server-side case, there might be a different issue. Let me check if renderToReadableStream actually calls getDerivedStateFromError during SSR.
According to React's source code, renderToReadableStream uses renderToSubstream internally. This function renders the element tree and handles errors via the onError callback. It doesn't call getDerivedStateFromError during the initial render.
So in SSR, if the global error component throws, getDerivedStateFromError might not be called. The onError callback is called instead, which logs the error and returns a digest string.
But wait, getDerivedStateFromError should still be called. Let me check React's documentation.
From React's docs:
getDerivedStateFromError is called during the render phase.
So it should be called during SSR. But the issue is that in SSR, the render happens once, and the result is sent to the client. If the component throws during the first render, getDerivedStateFromError catches it, and the component re-renders with the fallback. If the fallback also throws, getDerivedStateFromError is called again, and the component re-renders again.
So in SSR, the component should re-render with the simple fallback (if we implement the fix). But the issue says "renders no last-resort UI", which suggests that the component is not re-rendering with a fallback.
I think the issue might be that the global error component is throwing in a way that getDerivedStateFromError doesn't catch. For example, if the component is a class component that throws in its constructor, getDerivedStateFromError is not called (it's only called for render phase errors).
Or maybe the global error component is throwing synchronously during module initialization, before React even gets to render it.
Let me re-read the issue: "A self-throwing global error component renders no last-resort UI."
I think "self-throwing" means the global error component throws during its render method. So getDerivedStateFromError should be called.
But the issue is that when getDerivedStateFromError is called, it sets the error state and re-renders. On re-render, the same fallback is rendered, which throws again. This creates an infinite loop.
In React 18+, there's a mechanism to prevent this: the onCaughtError option. But the ErrorBoundaryInner doesn't use this option.
OK I think the issue is that React doesn't have a built-in mechanism to prevent infinite error loops in error boundaries. The ErrorBoundaryInner needs to implement its own mechanism to prevent this.
The mechanism I described earlier (tracking hasRenderedFallback) should work for this. Let me implement it now.
One more thing: the issue also mentions "preserving response headers and cookies". This means the fix should not clear any headers or cookies that were set before the error occurred.
In the vinext codebase, headers and cookies are managed by the server-side rendering pipeline. The ErrorBoundaryInner is a client-side component, so it doesn't have direct access to headers and cookies.
But the fix should not affect headers and cookies. The ErrorBoundaryInner just renders a simple HTML fallback when the component fallback throws. This doesn't clear any headers or cookies.
So the fix is straightforward:
- Modify ErrorBoundaryInner to track whether the fallback has been rendered
- If yes, render a simple HTML fallback
Let me implement this now.
Actually, I just realized something. The issue says "If the global error component itself fails, return the built-in valid HTML fallback with the expected successful fallback status while preserving response headers and cookies."
This suggests that the fix should be at a higher level than the ErrorBoundaryInner. It should be at the level of the fallback renderer or the page boundary renderer.
But looking at the code flow, the ErrorBoundaryInner is where the global error component is rendered. So the fix should be in the ErrorBoundaryInner.
OK let me just implement the fix and see if it works. I'll modify the ErrorBoundaryInner component to render a simple HTML fallback when the component fallback throws.
The implementation:
- Add an instance property
hasRenderedFallback to ErrorBoundaryInner
- In
render, check hasRenderedFallback before rendering the fallback. If true, render a simple HTML fallback.
- Reset
hasRenderedFallback when the error is cleared
Let me write the code.
Wait, actually, I want to reconsider the scope of the fix. The issue says:
- "If the global error component itself fails, return the built-in valid HTML fallback"
- "with the expected successful fallback status"
- "while preserving response headers and cookies"
- "Local error boundaries and framework navigation/control-flow signals must retain their existing semantics"
- "and the original boundary exception must not be exposed"
The key requirements are:
- Return valid HTML fallback
- Preserve headers and cookies
- Don't expose the original error
- Keep local error boundaries' semantics
I think the fix should be in the ErrorBoundaryInner component, which is used for both local error boundaries and global error. When the fallback throws, the ErrorBoundaryInner should render a simple HTML fallback.
But wait, ErrorBoundaryInner is used for local error boundaries too (not just global error). If a local error boundary's fallback throws, the ErrorBoundaryInner should also render a simple HTML fallback. This is consistent with the requirement: "Local error boundaries and framework navigation/control-flow signals must retain their existing semantics."
So the fix is general: whenever any error boundary's fallback throws, render a simple HTML fallback.
This is exactly what the hasRenderedFallback flag does. So I'll implement it.
Let me write the code now.
</tool_call>