ISSUE DESCRIPTION A self-throwing global error component renders no last-resort UI If…
- User
ISSUE DESCRIPTION
A self-throwing global error component renders no last-resort UI
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.
Interface
No new public interfaces are introduced.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
- If an error was reported in the issue description, I have successfully reproduced it.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
- I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /vinext, current file: none) bash-$
Assistant
I'll start by exploring the repository structure to understand what we're working with.
Assistant
Let me look for the global error handling files:
Assistant
Now let me look at the boundary file:
Assistant
Now I understand the structure. Let me also check the AppPageBoundary more deeply:
Assistant
Now let me understand the page-route-wiring file which has the error boundary usage:
Assistant
Now let me check the ErrorBoundary shim:
Assistant
Now let me look at the issue more carefully. The issue is about "a self-throwing global error component". This is the scenario where the global error component itself fails (throws an error during rendering). Let me search for how errors in the global error component might be handled:
Assistant
Let me look at how the global error boundary render works in detail:
Assistant
Now let me look at the part that handles the global error, especially the onError handler:
Assistant
Now let me look at where the global error is rendered. Let me look at the relevant RSC entry to understand the structure:
Assistant
Let me see the actual generation around the
globalErrorVarvariable:Assistant
Let me look at the RSC handler/render path:
Assistant
Now let me look at where
renderErrorBoundaryResponsecomes from:Assistant
Let me search where
renderErrorBoundaryPageis invoked:Assistant
Now I understand the architecture. The
renderAppPageErrorBoundaryfunction inapp-page-boundary-render.tsis where the global error is rendered. The issue says:A self-throwing global error component renders no last-resort UI
This means when the
global-error.tsxitself throws an error during rendering, we need to provide a last-resort UI. Let me check Next.js behavior:Assistant
Let me understand more context. The issue says:
A self-throwing global error component renders no last-resort UI
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 scenario is:
- An error happens in a page or layout
- The error propagates to the global error boundary
- The global error component itself throws during rendering
- Currently: no UI is rendered
- Expected: return the built-in valid HTML fallback (the default
DefaultGlobalErrorfromvinext/shims/default-global-error)
Let me check how
renderAppPageErrorBoundaryhandles this currently. The error boundary render just creates the React element and tries to render it. If the global error component throws, it would propagate.Let me trace where this happens. Look at
renderAppPageBoundaryElementResponse->renderAppPageBoundaryResponse:Assistant
Now let me look at the test files for app-page-boundary-render:
Assistant
Now let me see how the global error component is rendered in the renderAppPageErrorBoundary to understand how to add the last-resort fallback:
Assistant
Let me also check how Next.js handles this:
Assistant
Now let me look at the existing tests to understand the patterns:
Assistant
Now I understand the structure. Let me look at the boundary test file:
Assistant
Now let me write a small reproduction test. Let me look at how the global error is rendered when it throws:
Assistant
Now I need to understand the flow more deeply. Let me reproduce the issue first:
Assistant
Now let me understand how
renderAppPageBoundaryResponseis called from the global error path - what happens when the global error component itself throws. The issue is that when React tries to render the global error component but it throws, therenderToReadableStreamwill callonErrorcallback.Let me look at this in more detail. Looking at
renderAppPageBoundaryResponse:Assistant
OK now I see. When
renderToReadableStreamis called with the global error component element, and it throws during rendering, the onError handler is called. But for HTML output, we don't have any logic to recover from this case.Let me look at the html renderer:
Assistant
Now I have a clearer picture. The flow is:
- An error happens in a route's component
renderErrorBoundaryPageis called → calls__fallbackRenderer.renderErrorBoundaryrenderAppPageErrorBoundaryis invoked- It creates the element tree (page → layouts → global error boundary)
- RSC stream is created via
renderToReadableStream - SSR HTML is created from the RSC stream
When the global error component itself throws during rendering, what happens? Let me trace this more carefully. Let me check what
renderAppPageHtmlStreamWithRecoverydoes:Assistant
Now let me look at the issue more carefully. Let me trace what happens when the global error itself throws. Looking at the flow:
- The route rendering throws →
renderErrorBoundaryPagecalled __fallbackRenderer.renderErrorBoundary→renderAppPageErrorBoundaryrenderAppPageErrorBoundarybuilds element tree- The element tree includes the global error component
- Renders via
renderToReadableStream- this triggers the rendering - If the global error component throws, it's caught by React's onError handler
But wait, when does the global error component throw? It's a React element, so it could throw:
- Synchronously during render
- Async via promises
- In an effect (but global-error is a server-side render)
Looking at the
wrapRenderedBoundaryElementfunction for the global error case (isGlobalError: true),skipLayoutWrappingis set to true. Now if the global error component throws, the entire RSC render fails.Let me look at the SSR handler to see how errors during SSR are caught:
- The route rendering throws →
Assistant
Now let's write a reproduction. The key insight is: when
renderAppPageErrorBoundaryis called and the global error component itself throws, the SSR throws. The catch path goes torenderErrorBoundaryResponse→ which calls__fallbackRenderer.renderErrorBoundaryagain → but with what? This would be a recursive call, but at this pointerrorBoundary.isGlobalErroristrue. Let me trace.Actually, looking at it more carefully:
renderAppPageErrorBoundaryfirst does a synchronous element construction, thenrenderAppPageBoundaryElementResponsedoesrenderAppPageBoundaryResponsewhich callsrenderToReadableStreamwhich may NOT throw synchronously — errors in React render go to theonErrorcallback.Let me check more carefully.
renderToReadableStreamfor RSC... what does it do on error?The test helper
renderElementToStreamusesReactDOMServer.renderToStaticMarkupwhich is synchronous and would throw. But the real renderer is different.Let me check the actual
renderToReadableStreamimplementation:Assistant
OK so
renderToReadableStreamis essentiallyreact-dom/server.edge'srenderToReadableStream. Errors are captured inonError.Let me think about this differently. Let me reproduce the issue by writing a small test:
Assistant
Let me create a test in the existing test file structure:
Assistant
Let me check the existing test helper for boundary rendering:
Assistant
I see - my test should pass an
isRscRequest: trueand the renderer extracts the route. Let me update:Assistant
I forgot
vi. Let me fix:Assistant
I've reproduced the issue! When the global error component itself throws, the renderToReadableStream throws synchronously, and the error propagates out of
renderAppPageErrorBoundary. So we get no response, and no UI.Now let me think about the fix. The expected behavior is:
- When the global error component itself throws during rendering
- Return the built-in valid HTML fallback (
DefaultGlobalError) - Status: 200 (the expected successful fallback status)
- Preserve 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
Let me understand the structure better. The approach should be:
- In
renderAppPageErrorBoundary, detect if we're rendering the global error component (i.e.errorBoundary.isGlobalErroris true) - Wrap the rendering in a try/catch
- If it fails, fall back to
DefaultGlobalErrordirectly
Let me think about how to implement this:
Assistant
Now I understand the structure. The fix should:
- Wrap the rendering of the global error component in a try/catch
- On failure (only for
isGlobalError), render theDefaultGlobalErrordirectly
Let me check how
DefaultGlobalErroris structured (it's the shim's default export):Assistant
Now let me check the SSR pipeline to understand what happens. The issue is that
renderToReadableStreamis called on an element tree that includes the user-defined global error component. If it throws, the entire stream rendering throws.Now, the question is: should we wrap just the global error component's rendering, or the whole boundary render? Looking at Next.js's approach, the global error component itself acts as a boundary, so wrapping the entire rendering of the global error case should be safe. Let me look at how the issue says:
- "Local error boundaries and framework navigation/control-flow signals must retain their existing semantics"
So local error boundaries (non-global) should still throw normally (or be handled the existing way). Only the global error rendering needs the fallback.
Let me now think about implementation. Let me look at how 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"
The strategy:
- In
renderAppPageErrorBoundary, whenerrorBoundary.isGlobalErroris true, wrap the rendering in a try/catch
Assistant
Now let me understand the issue: where to wrap the try/catch. Let me think about this:
The cleanest place to add the fallback is inside
renderAppPageErrorBoundaryitself, because:- This is where the global error component is selected
- It already has access to
Assistant
OK so the flow is:
renderToReadableStreamis called - returns a streamcreateHtmlResponseis called to convert RSC stream to HTML- HTML response is returned
The key is: errors during RSC rendering go to
onErrorbut don't necessarily fail the stream.Now let me check how the SSR side handles errors during rendering. The SSR reads the RSC stream and renders it to HTML. If the RSC stream contains an error or invalid payload, the SSR may fail.
The simplest approach is to wrap the entire
renderAppPageBoundaryElementResponsecall in a try/catch, and when it's the global error case and we catch an error, fall back toDefaultGlobalError.Let me look at the issue once more:
Local error boundaries and framework navigation/control-flow signals must retain their existing semantics, and the original boundary exception must not be exposed.
This means:
- Local error boundaries (non-global) → existing behavior unchanged (throw or return response)
- Navigation/control-flow signals → still re-thrown (NEXT_REDIRECT, NEXT_NOT_FOUND, etc.)
- The original error → not exposed in the response body
Assistant
Now let me think about implementation strategy:
The cleanest approach is to wrap the
renderAppPageBoundaryElementResponsecall inrenderAppPageErrorBoundaryin a try/catch. When the global error component throws AND it's the global error boundary (isGlobalError: true), we catch it and fall back toDefaultGlobalError.Let me design this:
export async function renderAppPageErrorBoundary<TModule extends AppPageModule>( options: RenderAppPageErrorBoundaryOptions<TModule>, ): Promise<Response | null> { // ... existing setup ... const element = wrapRenderedBoundaryElement({...}); // Try rendering the boundary. If the global error component itself throws // during render, fall back to the built-in DefaultGlobalError so that // we always render *some* valid HTML. try { return await renderAppPageBoundaryElementResponse({...}); } catch (error) { if (!errorBoundary.isGlobalError) { throw error; // Local error boundaries retain existing semantics } if (isNavigationSignalError(error)) { throw error; // Navigation signals must propagate } // Fall back to DefaultGlobalError console.error( `[vinext] Global error boundary render failed for ${options.route?.pattern ?? pathname}; ` + `using built-in fallback UI:`, error, ); // Use the DefaultGlobalError component for fallback rendering const fallbackElement = createElement(DEFAULT_GLOBAL_ERROR_MODULE.default, { error: { digest: options.sanitizeErrorForClient(rawError).digest } }); // ... render fallback } }Assistant
OK, so I see that there's an existing pattern. Let me check what happens when a non-throwing global error (i.e.,
renderToReadableStreamsucceeds) but the resulting SSR HTML is empty/broken.Actually, let me check by writing a more realistic test that mimics how React's
renderToReadableStreambehaves:Assistant
Let me check how Next.js handles this. Let me search for "global error" handling in Next.js source:
Assistant
Let me search for "GlobalErrorComponent" usage in Next.js:
Assistant
OK, let me think differently. Let me search Next.js for where they handle a self-throwing global error:
Assistant
OK so Next.js has the same default. Now let me look at Next.js's approach. In Next.js, the global error is sent via the
Gfield in the RSC payload (the GlobalError). When the global error throws, the client-side ErrorBoundary catches it... but on the server, we still need to render something.Let me search for how Next.js handles this on the server:
Assistant
Looking at this, Next.js's strategy is to render the global error on the client (it sends the globalErrorStyles + GlobalError via the
Gfield). When the global error throws, the client catches it. The server mostly handles initial RSC payload errors.But the issue specifically says:
A self-throwing global error component renders no last-resort UI
This is about the server-rendered fallback. So we need a server-side fix.
Now let me think about this. Looking at our
renderAppPageErrorBoundary:const element = wrapRenderedBoundaryElement({ element: createElement( Fragment, null, ...headElements, createElement(errorBoundary.component, { error: errorObject, }), ), ... }); return renderAppPageBoundaryElementResponse({...});Assistant
Assistant
OK, the ErrorBoundary uses
usePathnamewhich is a client hook. So this isn't usable in RSC context.Let me try yet another approach. Let me directly wrap the global error component in a try/catch inside
renderAppPageErrorBoundary. The strategy:- Try to render the global error normally (catch any synchronous errors)
- Use a custom error tracker to detect if the global error threw during rendering
- If it did, fall back to rendering
DefaultGlobalErrordirectly
Let me look at how the rsc onError handler works:
Assistant
Assistant
OK so the NotFoundBoundary is similar. Let me check what happens in SSR for these boundaries:
Assistant
Assistant
OK that's the standard React
renderToReadableStream. Let me check its behavior in the docs:Actually, let me just write a more comprehensive test that uses the real renderer to see what happens:
Assistant
Interesting! In this case, the
renderToReadableStreamreturns something that doesn't havegetReader(it's the Flight format), but importantly, when consumed, it throws via a sync error in the underlying React. Let me check more:Assistant
Interesting! So
renderToReadableStreamreturns a Promise. When the underlying render fails, the promise REJECTS with the error. AndonErroris called.Let me test more:
Assistant
So
renderToReadableStreamreturns a Promise that REJECTS when rendering fails. The error is also captured byonError. This is exactly what I need.So the fix is straightforward: wrap the
renderToReadableStreamcall (or its caller) in a try/catch. On error, fall back.But wait, the existing code is:
const rscStream = runWithFetchDedupe(() => options.renderToReadableStream(options.element, { onError: options.createRscOnErrorHandler(), }), );It's NOT awaited, so if
renderToReadableStreamreturns a rejected promise, we'd have an unhandled rejection.Let me check:
Assistant
So if the promise is unhandled, we get an unhandled rejection. Now in the actual code, the
renderToReadableStreamis called and the returned promise is used. Let me see if it's awaited later or not:Assistant
OK so
renderAppPageBoundaryResponsedoesn't await the promise - it just passes the promise to the Response. The promise gets awaited when the response is consumed.So when the global error component throws:
renderToReadableStreamreturns a rejected promise- This promise is passed to
new Response(...) - When the response is consumed, the promise rejects → unhandled rejection
In
renderAppPageErrorBoundary, the flow:renderAppPageBoundaryElementResponseis called- This calls
renderAppPageBoundaryResponse - Which doesn't await the promise
- So no error is thrown here, but the promise is rejected later
Hmm, this complicates things. The error happens asynchronously when the response is consumed, not when we render.
But wait, in my test case, the error WAS thrown synchronously from
renderToReadableStream. Let me re-check:Assistant
The test uses
ReactDOMServer.renderToStaticMarkup(synchronous) wrapped in a ReadableStream. TherenderToReadableStreamin production returns a Promise. My test was passing a synchronous ReadableStream, so when React's sync renderer threw, the stream errored.Assistant
OK so
renderAppPageHtmlResponseis called and awaits the SSR rendering. If the rendering throws, the error propagates back.Now I have a clearer picture. The chain is:
renderAppPageErrorBoundary → renderAppPageBoundaryElementResponse → renderAppPageBoundaryResponse → options.createHtmlResponse (which is renderAppPageHtmlResponse) → renderAppPageHtmlStream → ssrHandler.handleSsr(rscStream) → reads RSC stream (which fails because global error threw) → throwsSo the error propagates from the SSR handler back to
renderAppPageBoundaryResponse→renderAppPageBoundaryElementResponse→renderAppPageErrorBoundary.Now the fix: wrap
renderAppPageBoundaryElementResponsein try/catch. If we catch an error ANDerrorBoundary.isGlobalErroris true, fall back to DefaultGlobalError.Let me verify this with a more realistic test:
Assistant
OK so the error is thrown synchronously. Now let me implement the fix.
Looking at the test:
- The
renderElementToStreamextracts the React element from the AppElements wrapper and renders it directly - When the global error throws, the renderer throws synchronously
- The error propagates up to
renderAppPageBoundaryResponse→ ... →renderAppPageErrorBoundary
Now I understand the test better. The error propagates synchronously up to the caller of
renderAppPageErrorBoundary. This means a try/catch inrenderAppPageErrorBoundarywould catch it.Now let me also handle the case where the error happens later (in real React server rendering with the actual ).
- The
Assistant
Now let me make the fix:
Assistant
Now let me look at how to use the
DEFAULT_GLOBAL_ERROR_MODULE:Assistant
Now let me write the fix:
Assistant
Let me now write the fix. I'll modify
renderAppPageErrorBoundary:Assistant
Now I need to make the edit. Let me look at the structure once more:
Assistant
Now let me edit the file to add the fallback logic:
Assistant
Good. Now let me modify the
renderAppPageErrorBoundaryfunction to add the fallback logic. Let me look at the current state of the file again:Assistant
Now let me make the fix:
Assistant
The edit was applied but bash mangled some content. Let me look at the file:
Assistant
The edit was applied but with issues. Let me fix the file properly. Let me undo the changes and re-apply them more carefully:
Assistant
The bash command munged the content. Let me reset and try again:
Assistant
Let me try a different approach - using a Python or bash heredoc for the edit:
Assistant
Let me verify:
Assistant
Now let me add the
renderAppPageGlobalErrorLastResorthelper function. Let me also verify the imports are correct:Assistant
Now let me add the helper function:
Assistant
Now let me check that there's no issue with the unused
pathnamevariable:Assistant
I notice the helper function has
pathnameas a parameter but doesn't use it. Let me check the usage and remove if not needed:Assistant
Let me remove the
pathnameparameter as it's not used:Assistant
Now let me check that the code compiles:
Assistant
Let me check the DefaultGlobalError props:
Assistant
The DefaultGlobalError expects
error: { digest?: string } | null | undefined. The sanitizer returns an Error. Let me handle this differently:Assistant
Good. So
sanitizeErrorForClientreturns either the original error (in dev) or an error with adigestproperty (in prod). Let me fix the typing:Assistant
Compiles. Now let me run my reproduction test:
Assistant
The fix works. The status is 200 and the body is the built-in DefaultGlobalError UI.
Let me check the body more carefully. I notice it's missing the
<p>ERROR ...</p>digest footer. Let me check the structure:Assistant
Both tests pass. Now let me also check the existing tests pass:
Assistant
Let me run more tests:
Assistant
All global-error tests pass. Let me also run more related tests:
Assistant
All tests pass. Now let me think about additional edge cases:
- Navigation signal errors: Already handled - we re-throw
- Non-global errors: Already handled - we re-throw to preserve existing semantics
- Headers/cookies preservation: The
renderAppPageBoundaryResponseautomatically merges middleware headers, so this should work
Let me also write a test for the headers/cookies preservation:
Assistant
All 5 tests pass. Let me also verify the final fix:
Assistant
Now let me look at one issue - the
renderAppPageBoundaryElementResponseis the inner function. Let me look at it again to see what happens with my call:Assistant
Good. The
renderAppPageBoundaryElementResponsewill use the passed options (which includesmiddlewareHeaders). So middleware headers are preserved.Now let me look at one issue. The DefaultGlobalError expects props:
type DefaultGlobalErrorProps = { error: { digest?: string } | null | undefined; reset?: () => void; };I'm passing
{ error: { digest: sanitizedError.digest } }. But what if the sanitized error doesn't have a digest (in dev mode, the original error is returned without digest)? Let me check:Assistant
Both dev and prod cases work correctly. Now let me also think about another scenario - what if the
DefaultGlobalErroritself throws? That shouldn't happen normally, but the issue mentions "If the global error component itself fails, return the built-in valid HTML fallback". If even the built-in throws, what should we do?The issue says we should return the built-in fallback, but doesn't say what to do if even that fails. For safety, we should let it throw in that case (since the built-in is supposed to never throw).
Let me check that the helper function's recursive fallback would also be caught by the outer try/catch... wait, the helper function is called from within the catch block, so if it throws, it would propagate out. That's the right behavior - if the built-in fallback fails, we let the error propagate.
Let me also think about another important case. What about when the
wrapRenderedBoundaryElementthrows? Looking at the helper:Assistant
The
wrapRenderedBoundaryElementis called inside the helper. If that throws, the helper throws, and that propagates out. Good.Let me also think about whether my fix handles the case where the global error module itself is null/undefined. Looking at the existing flow:
if (!errorBoundary.component) { return null; }If no component, returns null. So we never reach my code in that case. Good.
Now let me think about another edge case: what if the user has not defined a
global-error.tsx? ThenglobalErrorModuleis null, andeffectiveGlobalErrorModuleis the . In that case, the global error component is the built-in. If THAT throws (it shouldn't), we'd fall back to itself, which would loop... actually no, the fallback uses which is . The first attempt uses which is (same component). So if it throws, we try to render again - it would loop!Assistant
So
effectiveGlobalErrorModuleis either the user's module OR the built-in. The user-defined global error module is the candidate for being a "self-throwing" component. The built-in is the fallback.Assistant
All 124 tests pass. Now let me also run the page-render tests:
Assistant
All 131 tests pass. Let me also check the SSR-related tests:
Assistant
All passing. Now let me also look at how the issue is tested in real fixtures. Let me look at the existing global-error fixture:
Assistant
Now let me think about another edge case. What if the global error component itself uses
next/navigation'sredirect()ornotFound()? These are special signal errors with digests. The current fix correctly handles these viaisNavigationSignalError.But wait, can the global error component throw a navigation signal? Looking at the comment in shims/error-boundary.tsx:
// 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.So the navigation signals should propagate. My fix handles this correctly.
Let me also write an additional integration test to verify the fix works end-to-end. Let me also check the
app-router-dev-server.test.tsfile:Assistant
Let me run a broader test to make sure nothing's broken:
Assistant
All 163 tests pass. Now let me think about whether the issue requires me to test it as an integration test or just unit test. Looking at the test files for global-error, they use the
startFixtureServerhelper. Let me check if I can create a fixture for the self-throwing global error:Actually, let me first remove my temporary test file and then think about the right approach:
Assistant
Now let me think about whether I should add integration test fixtures. The issue says:
- No new public interfaces are introduced
So I shouldn't add new tests, fixtures, or interface. Just the fix.
Wait, but the checklist says I should:
- If an error was reported in the issue description, I have successfully reproduced it.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
- I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass.
I have done all of these. Let me also check what tests might be affected by my change. Let me search for tests that use
renderAppPageErrorBoundary:Assistant
Let me also look at the final code structure to ensure it's clean:
Assistant
Looks good. Now let me think about edge cases:
-
What if
sanitizeErrorForClientthrows? The error propagates out (we don't catch it). This is OK because we can't recover further. -
What if the
wrapRenderedBoundaryElementthrows (in the helper)? The error propagates out. -
What if
renderAppPageBoundaryElementResponsethrows in the helper (e.g., the built-in throws)? Error propagates out. -
What if
clearRequestContextwas already called by the failed render? Let me check:
-
Assistant
Good.
clearRequestContextis only called when the stream is fully consumed (indeferUntilStreamConsumed). If the render throws BEFORE the stream is consumed,clearRequestContextis NOT called. So my fallback rendering won't have the context already cleared.But wait, the user might have an error tracker that clears state on error. Let me check:
Assistant
Good. The
clearRequestContextis called when the stream is fully consumed. If the global error throws and we fall back, the stream wasn't fully consumed (it errored), soclearRequestContextwasn't called. The fallback render should still work because the request context is intact.Now let me think about another concern. The
renderAppPageBoundaryElementResponsein my fallback call doesn't includeisRscRequestcorrectly. Let me check:Assistant
Good.
isRscRequestis in the options. The...optionsspread passes it through.Now let me also check the actual error handling more carefully. Let me look at
renderAppPageBoundaryElementResponseto see what could throw:Assistant
The function itself shouldn't throw synchronously (the actual error happens during stream consumption). But the SSR handler might throw. Let me verify.
Looking at
renderAppPageBoundaryResponse:Assistant
OK, so for HTML responses,
createHtmlResponseis called - this isrenderAppPageHtmlResponse(an async function). When this function awaitsrenderAppPageHtmlStreamwhich awaitsssrHandler.handleSsr(rscStream)- if the rscStream rejects (because the global error threw), the error propagates through andrenderAppPageHtmlResponsethrows.For RSC responses, the rscStream is wrapped in a Response directly. The error would happen when the stream is consumed. But since my test was using a sync renderer (where the error throws synchronously in
renderToReadableStream), my test caught it at the await.OK now let me also verify the case where there's a real async error. Let me think about this:
Real scenario:
renderAppPageBoundaryResponsereturns aResponsewrapping aPromise<ReadableStream>
Assistant
OK so the
onRenderErrorcaptures errors during rendering. We could use this to detect async errors.But actually, for the
renderAppPageErrorBoundarycase (which is called as a fallback for the main render), the global error component is rendered as part of the RSC stream. Errors would go to theonErrorcallback.For RSC responses (where the stream is consumed by the client), we don't know if the global error threw until the stream is consumed. We can't proactively fall back.
Assistant
The real React
renderToReadableStreamalso propagates the error correctly. The error is caught by my try/catch, and the fallback DefaultGlobalError is rendered.Wait, I notice something interesting. The
onErrorwas called with "global error component crashed", thenstatus: 200and the body contains the default error HTML. This means the error from the global error component is being captured byonErrorAND the error propagates synchronously up through the rendering pipeline.Let me verify this more carefully. Let me also check what happens with
isRscRequest: true:Assistant
Both tests pass! But there's an unhandled rejection from the RSC stream. Let me look at this more carefully. The RSC request case (isRscRequest: true) returns a Response wrapping a stream. When the test doesn't consume the stream fully, the promise rejects but there's no one to catch it.
Assistant
So the stream errors when consumed. Let me clean up:
Assistant
Assistant
OK so the DefaultGlobalError handles both dev (no digest → generic message) and prod (with digest → "A server error occurred" + "ERROR " footer).
Let me now also think about whether the fix needs to be more conservative. What if my code path is also affected by the fact that
renderAppPageBoundaryElementResponsereturns a Response that may have lazy stream?Let me trace again:
- HTML:
createHtmlResponse(rscStream, status)→renderAppPageHtmlResponse(options)(where options.rscStream is the rscStream).renderAppPageHtmlResponseis async and awaitsrenderAppPageHtmlStream. If rscStream rejects when consumed, the error propagates back through the async chain. - RSC: returns
new Response(rscStream, ...)- no consumption, error happens lazily.
So for HTML, my try/catch catches it. For RSC, my try/catch doesn't catch it.
But the RSC case is for the
isRscRequest: truemode. In that mode, the client (browser) consumes the stream. If it errors, the client-side framework handles it. The server doesn't need to do anything special.But the issue says "return the built-in valid HTML fallback". So it's specifically for HTML mode. My fix handles this.
- HTML:
Assistant
OK so this is called when the main render fails. The
renderErrorBoundarymethod of the fallback renderer is called by the main app rendering pipeline.For HTML requests, when the main render fails:
- The error handler calls
renderErrorBoundary(which isrenderAppPageErrorBoundary) renderAppPageErrorBoundaryrenders the global error- If the global error throws, my fix catches it and renders the fallback
- Returns Response
For RSC requests, same as above. But the lazy error in RSC stream isn't caught.
Hmm wait, actually let me trace this more carefully. Let me check what
ssrHandler.handleSsrdoes:- The error handler calls
Assistant
This is the SSR rendering. It reads the RSC stream and converts to HTML. If the RSC stream errors during consumption, this would throw.
OK so for HTML requests, my fix correctly handles this. For RSC requests, the client-side framework handles the error.
Let me also verify by looking at what
renderAppPageBoundaryResponsedoes in more detail:Assistant
OK let me also do one more test to verify that the response stream doesn't have unhandled rejection issues:
Assistant
Let me think about what other tests I should run to verify:
Assistant
Let me run all the nextjs-compat tests to make sure nothing's broken:
Assistant
All 311 tests pass (with 2 skipped). Excellent!
Let me also run other related tests:
Assistant
All 234 tests pass.
Let me also run any other tests that might be affected:
Assistant
All 206 tests pass.
Let me also do a quick check that the type check passes:
Assistant
Type check passes.
Let me also run the linter:
Assistant
Linter passes too.
Now let me view the final diff to make sure it's clean:
Assistant
The diff looks clean. Let me also verify the file with one final test:
Assistant
All 4 tests pass. Let me clean up the temp test:
Assistant
Now let me check git status to see all changes:
Assistant
Only one file modified. Let me see the final diff once more to ensure correctness:
Assistant
The diff is clean. Let me also run a final check on all my relevant tests:
Assistant
All 454 tests pass.
Now let me re-verify the checklist:
Checklist:
Assistant
The code looks clean and complete.
Let me do one final check to make sure my fix doesn't have any hidden issues:
Assistant
All passing.
Let me submit:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.