Skip to content

build: phrase 3 - #2

Merged
abdelkabirouadoukou merged 6 commits into
mainfrom
build-phase-3
Jul 26, 2026
Merged

abdelkabirouadoukou merged 6 commits into
mainfrom
build-phase-3

Conversation

@abdelkabirouadoukou

@abdelkabirouadoukou abdelkabirouadoukou commented Jul 26, 2026 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features
    • Added API route handling with method-specific dispatch.
    • Added streaming server-side rendering.
    • Added route loaders with support for loader-provided data.
    • Added composable middleware with ancestor middleware discovery.
    • Added typed server functions accessible through generated clients.
    • Added HTML caching with TTL-based revalidation and manual cache invalidation.
  • Documentation
    • Updated the Phase 3 checklist to mark SSR, server functions, middleware, and revalidation capabilities as complete.
  • Tests
    • Added coverage for API routes, middleware, streaming, server functions, and revalidation behavior.

@coderabbitai

coderabbitai Bot commented Jul 26, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@abdelkabirouadoukou, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 24 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: e995c51a-525c-4e70-a521-f478066e6ebd

📥 Commits

Reviewing files that changed from the base of the PR and between 67798ed and 12d1cb0.

📒 Files selected for processing (6)
  • packages/core/src/build.ts
  • packages/core/src/createApp.ts
  • packages/core/src/index.ts
  • packages/core/src/render.ts
  • packages/core/src/router.ts
  • packages/core/src/server-functions.ts
📝 Walkthrough

Walkthrough

Phase 3 adds API route dispatch, streaming SSR, route loaders, middleware composition, server-function clients and handlers, TTL-based HTML caching, cache invalidation, and related tests and exports.

Changes

Phase 3 server runtime

Layer / File(s) Summary
Route classification and API dispatch
packages/core/src/router.ts, packages/core/src/build.ts, packages/core/src/createApp.ts, packages/core/src/index.ts, packages/core/src/phase3.test.ts
API routes are identified separately from page routes, included in generated server output, dispatched by HTTP method, and covered by route tests.
Loaders, streaming SSR, and revalidation
packages/core/src/render.ts, packages/core/src/createApp.ts, packages/core/src/phase3.test.ts
Page handlers pass loader data into routes, support streamed HTML rendering, cache static responses with TTLs, and handle cache invalidation requests.
Middleware discovery and composition
packages/core/src/router.ts, packages/core/src/middleware.ts, packages/core/src/createApp.ts, packages/core/src/index.ts, packages/core/src/phase3.test.ts
Ancestor middleware files are discovered and composed around page handlers with ordering, short-circuiting, and duplicate-next() protection.
Server-function registration and clients
packages/core/src/server-functions.ts, packages/core/src/build.ts, packages/core/src/createApp.ts, packages/core/src/index.ts, packages/core/src/phase3.test.ts
Generated clients call action endpoints, exported server functions are registered, and POST requests dispatch handlers and return JSON results.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant createApp
  participant RouteLoader
  participant renderStreamingPage
  Client->>createApp: Request page route
  createApp->>RouteLoader: Load route data
  RouteLoader-->>createApp: Return loader data
  createApp->>renderStreamingPage: Render page
  renderStreamingPage-->>Client: Stream HTML response
Loading
sequenceDiagram
  participant GeneratedClient
  participant serverFnHandler
  participant ACTION_ROUTES
  participant ServerFunction
  GeneratedClient->>serverFnHandler: POST action arguments
  serverFnHandler->>ACTION_ROUTES: Resolve route and action
  ACTION_ROUTES->>ServerFunction: Invoke handler
  ServerFunction-->>GeneratedClient: Return JSON result
Loading

Possibly related PRs

  • abdelkabirouadoukou/x#1: Earlier build and rendering groundwork overlaps with the server entry and HTML rendering changes.
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title is too vague to convey the main change in this PR. Use a concise, specific title that names the primary change, such as SSR, API routes, middleware, or server functions.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch build-phase-3

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 14

🧹 Nitpick comments (5)
packages/core/src/router.ts (1)

137-155: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

findMiddlewareChain duplicates findLayoutChain verbatim.

Lines 137-155 are identical to Lines 96-114 apart from the entry type. Both entry types share { filePath, dirPath }, so a single generic walker would do.

♻️ Suggested consolidation
+function findChain<T extends { dirPath: string }>(
+  routeFilePath: string,
+  entries: T[],
+  routesDir: string,
+): T[] {
+  const chain: T[] = [];
+  let current = join(routeFilePath, "..");
+  while (current.startsWith(routesDir)) {
+    const found = entries.find((e) => e.dirPath === current);
+    if (found) chain.unshift(found);
+    const parent = join(current, "..");
+    if (parent === current) break;
+    current = parent;
+  }
+  return chain;
+}
+
 export function findMiddlewareChain(
   routeFilePath: string,
   middleware: MiddlewareEntry[],
   routesDir: string,
 ): MiddlewareEntry[] {
-  const routeDir = join(routeFilePath, "..");
-  const chain: MiddlewareEntry[] = [];
-
-  let current = routeDir;
-  while (current.startsWith(routesDir)) {
-    const mw = middleware.find((m) => m.dirPath === current);
-    if (mw) chain.unshift(mw);
-    const parent = join(current, "..");
-    if (parent === current) break;
-    current = parent;
-  }
-
-  return chain;
+  return findChain(routeFilePath, middleware, routesDir);
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/router.ts` around lines 137 - 155, Consolidate the
duplicated directory-walking logic in findMiddlewareChain and findLayoutChain
into one generic helper that operates on entries sharing filePath and dirPath,
then have both functions delegate to it while preserving their existing return
types and chain ordering.
packages/core/src/middleware.ts (1)

10-27: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

composeMiddleware discards the next it advertises.

The returned function is typed MiddlewareFn, so callers must supply a next, but _next is never invoked — the terminal handler is always handler. In createApp.ts Lines 254-257 the Not found fallback is therefore dead code. Return (ctx: MiddlewareContext) => Promise<Response> instead so the contract matches behaviour.

♻️ Suggested change
 export function composeMiddleware(
   fns: MiddlewareFn[],
   handler: (ctx: MiddlewareContext) => Promise<Response>,
-): MiddlewareFn {
-  return async (ctx, _next) => {
+): (ctx: MiddlewareContext) => Promise<Response> {
+  return async (ctx) => {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/middleware.ts` around lines 10 - 27, Update
composeMiddleware so its returned function is typed as (ctx: MiddlewareContext)
=> Promise<Response> rather than MiddlewareFn, matching the implementation that
ignores _next and always terminates through handler. Keep the existing dispatch
and middleware chaining behavior unchanged.
packages/core/src/phase3.test.ts (2)

170-177: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

{ ...res } spreads nothing.

Response exposes its fields via prototype getters, so the spread contributes no own enumerable properties — status silently falls back to 200 rather than being copied. Copy explicitly if that was the intent.

♻️ Suggested change
       return new Response(res.body, {
-        ...res,
-        headers: { "x-custom": "true" },
+        status: res.status,
+        statusText: res.statusText,
+        headers: { "x-custom": "true" },
       });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/phase3.test.ts` around lines 170 - 177, Update the response
reconstruction in the “single middleware works” test to copy the intended
Response properties explicitly instead of spreading res. Preserve the existing
response body and custom header while ensuring status and other relevant
metadata from the result of next() are retained.

302-319: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Test asserts only the response text, not that the cache was cleared.

Add a follow-up request asserting X-Revalidated: miss for both /isr-static and /pure-static after the flush; otherwise this passes even if staticCache.clear() is removed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/phase3.test.ts` around lines 302 - 319, Extend the test
“/__x/revalidate with no path clears all caches” after the revalidation response
by fetching both /isr-static and /pure-static again and asserting each response
has X-Revalidated set to “miss”, while retaining the existing “Revalidated all”
assertion.
packages/core/src/render.ts (1)

104-120: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Prefer a loop over recursive pump, and release the reader.

Each chunk adds a retained async frame for the lifetime of the response; a while loop is flat and lets you releaseLock()/controller.error() on failure.

♻️ Suggested change
   return new ReadableStream({
     async start(controller) {
       controller.enqueue(encoder.encode(header));
       const reader = reactStream.getReader();
-      async function pump(): Promise<void> {
-        const { done, value } = await reader.read();
-        if (done) {
-          controller.enqueue(encoder.encode(`</div>\n    ${footer}`));
-          controller.close();
-          return;
-        }
-        controller.enqueue(value);
-        await pump();
-      }
-      await pump();
+      try {
+        while (true) {
+          const { done, value } = await reader.read();
+          if (done) break;
+          controller.enqueue(value);
+        }
+        controller.enqueue(encoder.encode(`</div>\n    ${footer}`));
+        controller.close();
+      } catch (err) {
+        controller.error(err);
+      } finally {
+        reader.releaseLock();
+      }
     },
   });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/render.ts` around lines 104 - 120, Update the
ReadableStream start handler around the local pump function to replace recursive
reads with a loop that processes chunks until done, preserving the footer
enqueue and controller close behavior. Ensure the reader lock is released after
processing, and route read or enqueue failures through controller.error() while
still releasing the reader.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/core/src/build.ts`:
- Around line 306-317: Update handleApiRoute to return Response |
Promise<Response> | null and preserve the handler’s async result when invoking
handlers; keep the 405 response for unsupported methods and null result for
unmatched routes unchanged.
- Around line 283-292: Update the apiImports generation in the build flow to use
namespace imports for each API module, matching the named-export contract
consumed by apiEntries and createApp. Keep the existing
Api${i}.GET/POST/PUT/PATCH/DELETE handler references unchanged.
- Line 309: Update the route pattern construction in toRouteEntry to escape
literal route text, preserve named parameter replacement as a capturing segment,
and translate emitted catch-all "*" segments into an explicit capture matching
the remaining path. Ensure regex metacharacters in literal route portions are
treated literally.

In `@packages/core/src/createApp.ts`:
- Around line 62-67: Change isServerFunction and the related registration flow
to opt in only explicitly declared server actions, such as functions listed in
an actions export or originating from files with a "use server" directive,
instead of treating every non-reserved export as callable. Update the action
request handling around the server-action registration and POST endpoint so
requests pass through the existing middleware chain before invocation, while
preserving the current reserved-export and HTTP-method exclusions.
- Around line 224-241: Use the resolved request pathname from new
URL(ctx.request.url).pathname as the staticCache key in the cache lookup and
write flow around the revalidation logic, replacing route.routePath. Keep the
invalidation logic around staticCache.delete(body.path) unchanged because it
will then target the same key; apply the key change at
packages/core/src/createApp.ts lines 224-241, with
packages/core/src/createApp.ts lines 284-295 requiring no direct change.
- Around line 216-222: Update the server branch around renderStreamingPage in
createApp so rejected streaming renders are caught and converted into a 500
error response, or fall back to renderPage using the existing error-handling
behavior. Preserve the successful streaming Response path and ensure
shell/render exceptions do not escape as unhandled rejections.
- Around line 141-150: Update the request handler around handlerFn so results
that are undefined do not pass to Response.json, which rejects them. Return an
appropriate successful empty Response for undefined results, while preserving
direct Response returns and JSON conversion for defined values.
- Around line 284-295: Secure handleRevalidation by requiring the established
application authentication mechanism before allowing cache deletion, returning
an appropriate unauthorized response for unauthenticated requests. Also parse
the request body defensively so empty or malformed JSON does not throw an
unhandled error; preserve path-specific deletion for valid bodies and only clear
the entire staticCache when the request is valid and intentionally omits a path.

In `@packages/core/src/render.ts`:
- Around line 29-47: Update htmlShell to stop escaping its title argument, since
renderPage and renderStaticPage already pass escaped titles and
renderStreamingPage follows the same contract. Preserve the existing title
interpolation while ensuring each title is escaped exactly once.
- Line 100: Update renderStreamingPage around renderToReadableStream to provide
an onError callback for component and Suspense rendering failures, and wrap the
streaming call in try/catch so fatal shell errors produce the established safe
error response instead of propagating an errored stream directly to
createApp.ts.

In `@packages/core/src/router.ts`:
- Around line 44-47: Update isApi in toRouteEntry to derive API detection from
the existing segments array, matching only an exact "api" path segment and using
the platform-independent split result. Preserve non-API names such as apiary and
apis.tsx as regular pages, while correctly detecting nested API directories on
all platforms.

In `@packages/core/src/server-functions.ts`:
- Around line 43-54: Update the ACTION_ROUTES registry lifecycle so rebuilds do
not retain deleted, renamed, or stale server actions. Either export a reset
function for ACTION_ROUTES and invoke it at the start of createApp’s
buildHandlers flow, or replace each route’s map rather than merging; ensure
every rebuild reflects only the currently registered functions.
- Around line 56-72: Update getServerFunctionHandler so action routes resolve
using the registered route pattern, not only an exact concrete routePath lookup.
Reuse the existing normal-route pattern matching mechanism to match
parameterized paths such as /posts/:id, then retrieve the action by actionName
from the matched route’s actions while preserving null for unmatched routes.
- Around line 74-81: Update the server-function request handler to validate the
HTTP method before registry lookups, returning 405 for every non-POST request.
Safely parse the body and require an array before invoking fn(...args); convert
empty or malformed JSON and non-array payloads into a controlled 4xx response
instead of allowing req.json() or the spread call to throw.

---

Nitpick comments:
In `@packages/core/src/middleware.ts`:
- Around line 10-27: Update composeMiddleware so its returned function is typed
as (ctx: MiddlewareContext) => Promise<Response> rather than MiddlewareFn,
matching the implementation that ignores _next and always terminates through
handler. Keep the existing dispatch and middleware chaining behavior unchanged.

In `@packages/core/src/phase3.test.ts`:
- Around line 170-177: Update the response reconstruction in the “single
middleware works” test to copy the intended Response properties explicitly
instead of spreading res. Preserve the existing response body and custom header
while ensuring status and other relevant metadata from the result of next() are
retained.
- Around line 302-319: Extend the test “/__x/revalidate with no path clears all
caches” after the revalidation response by fetching both /isr-static and
/pure-static again and asserting each response has X-Revalidated set to “miss”,
while retaining the existing “Revalidated all” assertion.

In `@packages/core/src/render.ts`:
- Around line 104-120: Update the ReadableStream start handler around the local
pump function to replace recursive reads with a loop that processes chunks until
done, preserving the footer enqueue and controller close behavior. Ensure the
reader lock is released after processing, and route read or enqueue failures
through controller.error() while still releasing the reader.

In `@packages/core/src/router.ts`:
- Around line 137-155: Consolidate the duplicated directory-walking logic in
findMiddlewareChain and findLayoutChain into one generic helper that operates on
entries sharing filePath and dirPath, then have both functions delegate to it
while preserving their existing return types and chain ordering.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: ab5c3692-eed7-4c48-86c8-5bbb69d3271a

📥 Commits

Reviewing files that changed from the base of the PR and between 72e271f and 67798ed.

📒 Files selected for processing (10)
  • TASKS.md
  • packages/core/src/build.ts
  • packages/core/src/createApp.ts
  • packages/core/src/index.ts
  • packages/core/src/middleware.ts
  • packages/core/src/phase3.test.ts
  • packages/core/src/render.ts
  • packages/core/src/router.ts
  • packages/core/src/server-functions.ts
  • packages/core/tsconfig.json

Comment thread packages/core/src/build.ts Resolved
Comment thread packages/core/src/build.ts Resolved
Comment thread packages/core/src/build.ts Resolved
Comment thread packages/core/src/createApp.ts Resolved
Comment thread packages/core/src/createApp.ts Resolved
Comment thread packages/core/src/render.ts Outdated
: "";
const footer = `${propsScript ? ` ${propsScript}\n` : ""}${scripts ? ` ${scripts}\n` : ""} </body>\n</html>`;

const reactStream = await renderToReadableStream(node);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== files =="
git ls-files | rg '(^|/)render\.ts$|(^|/)createApp\.ts$|package\.json$' || true

echo "== render.ts outline =="
for f in $(git ls-files | rg '(^|/)render\.ts$'); do
  echo "--- $f"
  wc -l "$f"
  ast-grep outline "$f" || true
  echo "--- relevant lines"
  sed -n '1,220p' "$f" | cat -n
done

echo "== createApp.ts files and render usage =="
for f in $(git ls-files | rg '(^|/)createApp\.ts$'); do
  echo "--- $f"
  wc -l "$f"
  ast-grep outline "$f" || true
  rg -n "renderToReadableStream|try\\b|catch|onError|render|node" "$f" -C 5 || true
done

echo "== renderToReadableStream references =="
rg -n "renderToReadableStream|onError" . -g '!node_modules' -g '!dist' -g '!build' || true

Repository: abdelkabirouadoukou/x

Length of output: 14169


🌐 Web query:

React renderToReadableStream options.onError stream reported error promise rejected documentation

💡 Result:

In React, the renderToReadableStream API provides an optional onError callback used for logging and error reporting [1][2]. Key behaviors regarding the onError callback and promise rejection: 1. onError Callback: This callback is triggered whenever a server-side error occurs during the rendering process, regardless of whether the error is recoverable (e.g., inside a Suspense boundary) or fatal [1][3]. It is primarily intended for logging errors to your monitoring service [1][2][3]. You should ensure you call console.error within this callback if you override it, as the default behavior performs this action [1][3]. 2. Promise Rejection: The renderToReadableStream function returns a Promise that resolves to a ReadableStream [1][4][3]. - If the initial "shell" of your application renders successfully, the Promise resolves [3][5]. - If a fatal error occurs while generating the shell—meaning React cannot produce a meaningful initial HTML response—the Promise will reject [3][5]. 3. Handling Errors: Because both onError and a catch block will fire if the shell fails to render, you should adopt a strategy that separates reporting from recovery [1][3]: - Use the onError callback for logging crash reports and observability [1][2][3]. - Wrap the renderToReadableStream call in a try/catch block to handle fatal shell rendering errors [1][3]. In the catch block, you should return a fallback HTML document or an alternative shell that allows the application to render on the client side [1][3][5]. Example Usage: async function handler(request) { try { const stream = await renderToReadableStream(, { onError(error) { console.error(error); // Log the error for observability [1][3] logServerCrashReport(error); } }); return new Response(stream, { headers: { 'content-type': 'text/html' } }); } catch (error) { // Handle fatal shell failure [1][3] return new Response('

Something went wrong

', { status: 500, headers: { 'content-type': 'text/html' } }); } }

Citations:


🌐 Web query:

React 17 renderToReadableStream does onError default console.error option documentation

💡 Result:

In React, the renderToReadableStream API includes an optional onError callback option. This callback is triggered whenever a server-side error occurs during rendering, whether the error is recoverable or non-recoverable [1][2]. Key details regarding the onError option: Default Behavior: By default, if no onError callback is provided, React automatically logs the error using console.error [1][2]. Overriding: If you choose to provide a custom onError callback to handle tasks like logging crash reports or tracking metrics, it is recommended to manually call console.error(error) within your implementation to maintain the standard error logging behavior [1][2]. Function Signature: The callback receives the error object, and in some definitions, an additional errorInfo object containing more context [3]. Usage for Status Codes: You can use the onError callback to track whether an error has occurred, which allows you to adjust the HTTP status code (e.g., to 500) before the initial shell is emitted to the client [1][2]. It is important to note that if an error occurs while generating the shell itself, both the onError callback and any surrounding try...catch block (wrapping the renderToReadableStream call) will fire. React documentation suggests using onError specifically for error reporting/logging and utilizing a try...catch block to send fallback HTML to the client [1][2].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== package react-dom versions =="
for f in package.json examples/basic/package.json packages/cli/package.json packages/core/package.json; do
  echo "--- $f"
  jq -r '.dependencies."react-dom", .devDependencies."react-dom", .peerDependencies."react-dom"' "$f" 2>/dev/null || cat "$f"
done

echo "== createApp failure paths around handlers =="
sed -n '137,360p' packages/core/src/createApp.ts | cat -n

echo "== import/type usage for React DOM version =="
rg -n '"react-dom"|react-dom/server' packages/core/src createApp.ts render.ts package.json -C 2 || true

Repository: abdelkabirouadoukou/x

Length of output: 10216


🌐 Web query:

React server components renderToReadableStream without onError callback error silently node_modules react-dom/server onError

💡 Result:

The onError callback in renderToReadableStream is not intended to handle all types of failures, which can sometimes give the impression of silent errors if you rely solely on it [1][2]. Key aspects of error handling with renderToReadableStream: 1. onError vs. try...catch: The onError callback is designed to capture errors that occur during rendering (both recoverable errors within Suspense boundaries and some unrecoverable ones) [1][3]. However, if an error occurs while generating the initial shell, the promise returned by renderToReadableStream will reject [3]. You must wrap the renderToReadableStream call in a try...catch block to handle these shell-generation errors, as the onError callback alone may not be sufficient or triggered in time for fatal startup issues [2][3][4]. 2. Default Behavior: By default, the onError callback calls console.error [1]. If you override it, you must manually call console.error if you want to maintain the default logging behavior [1][3]. 3. Node.js Environment Context: Historically, renderToReadableStream was not fully supported or intended for use in Node.js, which led to confusion and potential issues with imports in older versions (pre-React 19.2) [5][6][7]. Ensure you are using a modern version of React (19.2+) that officially supports Web Streams in Node.js to avoid environment-specific bugs [6]. 4. Recommended Pattern: To ensure no errors are handled silently, use both a try...catch block and the onError callback [2][4]: - try...catch: Handles errors that prevent the stream promise from resolving (e.g., shell generation failure). - onError: Handles errors that occur during the streaming process (e.g., components inside Suspense boundaries failing). Example Implementation: async function handler(request) { let didError = false; try { const stream = await renderToReadableStream(, { onError(error) { didError = true; console.error(error); // Ensure logging } }); return new Response(stream, { status: didError? 500: 200, headers: { 'content-type': 'text/html' }, }); } catch (error) { // Handle fatal shell rendering errors return new Response('

Internal Server Error

', { status: 500, headers: { 'content-type': 'text/html' }, }); } }

Citations:


Add render error handling for renderStreamingPage.

renderStreamingPage passes no onError to renderToReadableStream, so component/Suspense rendering errors can be logged only by React’s default handler or surfacing as an errored stream; the route handler in createApp.ts also forwards stream failures directly to the response without a fallback or 500 handling. Pass an onError callback, and wrap the React streaming call in try/catch to return a safe error response for fatal shell rendering failures.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/render.ts` at line 100, Update renderStreamingPage around
renderToReadableStream to provide an onError callback for component and Suspense
rendering failures, and wrap the streaming call in try/catch so fatal shell
errors produce the established safe error response instead of propagating an
errored stream directly to createApp.ts.

Comment thread packages/core/src/router.ts Resolved
Comment thread packages/core/src/server-functions.ts Resolved
Comment thread packages/core/src/server-functions.ts Resolved
Comment thread packages/core/src/server-functions.ts Outdated
Comment on lines +74 to +81
if (req.method !== "POST") {
return new Response("Method not allowed", { status: 405 });
}

const args = (await req.json()) as unknown[];
const result = await fn(...args);
return Response.json(result);
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Unvalidated request body and late method check.

await req.json() (Line 78) throws on an empty/malformed body and fn(...args) throws TypeError when the payload isn't an array — both surface as unhandled 500s from attacker-controlled input. The method check also runs after the registry lookups, so a GET to an unknown action returns 404 while a known one returns 405; move it up.

🛡️ Proposed fix
-    const routeActions = ACTION_ROUTES.get(routePath);
+    if (req.method !== "POST") {
+      return new Response("Method not allowed", { status: 405 });
+    }
+
+    const routeActions = ACTION_ROUTES.get(routePath);
     if (!routeActions) return null;
 
     const fn = routeActions.get(actionName);
     if (!fn) return null;
 
-    if (req.method !== "POST") {
-      return new Response("Method not allowed", { status: 405 });
-    }
-
-    const args = (await req.json()) as unknown[];
-    const result = await fn(...args);
-    return Response.json(result);
+    let args: unknown;
+    try {
+      args = await req.json();
+    } catch {
+      return new Response("Invalid JSON body", { status: 400 });
+    }
+    if (!Array.isArray(args)) {
+      return new Response("Expected an array of arguments", { status: 400 });
+    }
+
+    const result = await fn(...args);
+    return Response.json(result ?? null);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/server-functions.ts` around lines 74 - 81, Update the
server-function request handler to validate the HTTP method before registry
lookups, returning 405 for every non-POST request. Safely parse the body and
require an array before invoking fn(...args); convert empty or malformed JSON
and non-array payloads into a controlled 4xx response instead of allowing
req.json() or the spread call to throw.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant