Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Report and log RSC loader, action and middleware errors by default
  • Loading branch information
brookslybrand committed Oct 20, 2026
commit 86966192241a62589094f2ca26983185cd12dff0
153 changes: 153 additions & 0 deletions integration/rsc-server-error-logging-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import { test, expect } from "@playwright/test";

import { createFixture, js } from "./helpers/create-fixture.js";
import type { Fixture } from "./helpers/create-fixture.js";

// These tests use the `rsc-vite-framework` template without custom
// `entry.rsc.tsx` / `entry.ssr.tsx` files, so they exercise the default RSC
// Framework Mode entries in `@react-router/dev/config/default-rsc-entries`.

test.describe("RSC Framework: server error logging", () => {
let fixture: Fixture;
let originalConsoleError: typeof console.error;
let logged: unknown[][];

test.beforeAll(async () => {
fixture = await createFixture({
templateName: "rsc-vite-framework",
files: {
// Give the root an ErrorBoundary so the built-in default root
// boundary (which calls `console.error`) never renders
"app/root.tsx": js`
import { Links, Meta, Outlet, ScrollRestoration } from "react-router";

export function Layout({ children }) {
return (
<html lang="en">
<head>
<Meta />
<Links />
</head>
<body>
{children}
<ScrollRestoration />
</body>
</html>
);
}

export default function App() {
return <Outlet />;
}

export function ErrorBoundary() {
return <h1 id="error-boundary">ROOT_ERROR_BOUNDARY</h1>;
}
`,
"app/routes/loader-error.tsx": js`
export function loader() {
throw new Error("LOADER_ERROR_MESSAGE");
}

export default function LoaderError() {
return <h1>LOADER_ERROR_ROUTE</h1>;
}
`,
"app/routes/action-error.tsx": js`
export function action() {
throw new Error("ACTION_ERROR_MESSAGE");
}

export default function ActionError() {
return <h1>ACTION_ERROR_ROUTE</h1>;
}
`,
"app/routes/resource-error.tsx": js`
export function loader() {
throw new Error("RESOURCE_ERROR_MESSAGE");
}
`,
"app/server-functions.ts": js`
"use server";

export async function failingServerFunction() {
throw new Error("SERVER_FUNCTION_ERROR_MESSAGE");
}
`,
"app/routes/server-function-error.tsx": js`
import { failingServerFunction } from "../server-functions";

export function ServerComponent() {
return (
<form action={failingServerFunction}>
<button type="submit">Submit</button>
</form>
);
}
`,
},
});
});

// The fixture's request helpers run the built server handler in this
// process, so we can observe what it logs
test.beforeEach(() => {
logged = [];
originalConsoleError = console.error;
console.error = (...args: unknown[]) => {
logged.push(args);
};
});

test.afterEach(() => {
console.error = originalConsoleError;
});

function expectLogged(message: string) {
let messages = logged
.flat()
.map((arg) => (arg instanceof Error ? arg.message : String(arg)));
expect(messages.join("\n")).toContain(message);
}

test("logs errors thrown from loaders", async () => {
let response = await fixture.requestDocument("/loader-error");
expect(response.status).toBe(500);
expect(await response.text()).toContain("ROOT_ERROR_BOUNDARY");
expectLogged("LOADER_ERROR_MESSAGE");
});

test("logs errors thrown from actions", async () => {
let response = await fixture.postDocument(
"/action-error",
new URLSearchParams({ intent: "fail" }),
);
expect(response.status).toBe(500);
expect(await response.text()).toContain("ROOT_ERROR_BOUNDARY");
expectLogged("ACTION_ERROR_MESSAGE");
});

test("logs errors thrown from resource routes", async () => {
let response = await fixture.requestResource("/resource-error");
expect(response.status).toBe(500);
await response.text();
expectLogged("RESOURCE_ERROR_MESSAGE");
});

test("logs errors thrown from server functions", async () => {
let html = await (
await fixture.requestDocument("/server-function-error")
).text();
let actionField = html.match(/name="(\$ACTION_ID_[^"]+)"/)?.[1];
expect(actionField).toBeTruthy();

let formData = new FormData();
formData.append(actionField!, "");
let response = await fixture.requestDocument("/server-function-error", {
method: "POST",
body: formData,
});
await response.text();
expectLogged("SERVER_FUNCTION_ERROR_MESSAGE");
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Report loader, action and middleware errors to `matchRSCServerRequest`'s `onError` and log errors with `console.error` by default when no `onError` is provided, matching non-RSC Framework Mode
154 changes: 154 additions & 0 deletions packages/react-router/__tests__/rsc/server-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,160 @@ describe("RSC server", () => {
});
});
});

describe("error reporting", () => {
let consoleError: jest.SpyInstance;

beforeEach(() => {
consoleError = jest.spyOn(console, "error").mockImplementation(() => {});
});

afterEach(() => {
consoleError.mockRestore();
});

let errorRoutes: RSCRouteConfigEntry[] = [
{
id: "root",
path: "/",
Component: () => null,
ErrorBoundary: () => null,
children: [
{
id: "loader-error",
path: "loader-error",
Component: () => null,
loader() {
throw new Error("LOADER_ERROR");
},
},
{
id: "action-error",
path: "action-error",
Component: () => null,
action() {
throw new Error("ACTION_ERROR");
},
},
{
id: "thrown-response",
path: "thrown-response",
Component: () => null,
loader() {
throw new Response("Nope", { status: 401 });
},
},
{
id: "middleware-error",
path: "middleware-error",
Component: () => null,
middleware: [
() => {
throw new Error("MIDDLEWARE_ERROR");
},
],
},
],
},
];

function matchErrorRequest(
request: Request,
onError?: (error: unknown) => void,
) {
return matchRSCServerRequest({
createTemporaryReferenceSet: () => ({}),
request,
routes: errorRoutes,
onError,
generateResponse(match) {
return new Response(null, { status: match.statusCode });
},
});
}

test("calls onError with loader errors", async () => {
let onError = jest.fn();
let response = await matchErrorRequest(
new Request("https://remix.run/loader-error"),
onError,
);
expect(response.status).toBe(500);
expect(onError).toHaveBeenCalledTimes(1);
expect(onError.mock.calls[0][0]).toEqual(new Error("LOADER_ERROR"));
});

test("calls onError with loader errors on data requests", async () => {
let onError = jest.fn();
await matchErrorRequest(
new Request("https://remix.run/loader-error.rsc"),
onError,
);
expect(onError).toHaveBeenCalledTimes(1);
expect(onError.mock.calls[0][0]).toEqual(new Error("LOADER_ERROR"));
});

test("calls onError with action errors", async () => {
let onError = jest.fn();
let response = await matchErrorRequest(
new Request("https://remix.run/action-error", {
method: "POST",
body: new URLSearchParams({ a: "b" }),
}),
onError,
);
expect(response.status).toBe(500);
expect(onError).toHaveBeenCalledTimes(1);
expect(onError.mock.calls[0][0]).toEqual(new Error("ACTION_ERROR"));
});

test("calls onError with middleware errors", async () => {
let onError = jest.fn();
await matchErrorRequest(
new Request("https://remix.run/middleware-error"),
onError,
);
expect(onError).toHaveBeenCalledTimes(1);
expect(onError.mock.calls[0][0]).toEqual(new Error("MIDDLEWARE_ERROR"));
});

test("does not call onError with thrown responses", async () => {
let onError = jest.fn();
let response = await matchErrorRequest(
new Request("https://remix.run/thrown-response"),
onError,
);
expect(response.status).toBe(401);
expect(onError).not.toHaveBeenCalled();
});

test("logs errors with console.error when no onError is provided", async () => {
await matchErrorRequest(new Request("https://remix.run/loader-error"));
expect(consoleError).toHaveBeenCalledTimes(1);
expect(consoleError.mock.calls[0][0]).toEqual(new Error("LOADER_ERROR"));
});

test("logs the underlying error for internal error responses", async () => {
await matchErrorRequest(new Request("https://remix.run/does-not-exist"));
expect(consoleError).toHaveBeenCalledTimes(1);
expect(consoleError.mock.calls[0][0]).toBeInstanceOf(Error);
expect(consoleError.mock.calls[0][0].message).toMatch(
'No route matches URL "/does-not-exist"',
);
});

test("does not log errors for aborted requests", async () => {
let controller = new AbortController();
let response = matchErrorRequest(
new Request("https://remix.run/loader-error", {
signal: controller.signal,
}),
);
controller.abort();
await response.catch(() => {});
expect(consoleError).not.toHaveBeenCalled();
});
});
});

async function matchManifestRequest(
Expand Down
21 changes: 20 additions & 1 deletion packages/react-router/lib/rsc/server.rsc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,8 @@ export type RouteDiscovery =
* @param opts.clientVersion A version derived from the client build output used
* to detect stale clients during lazy route discovery.
* @param opts.onError An optional error handler that will be called with any
* errors that occur during the request processing.
* errors that occur during the request processing. Defaults to logging errors
* with `console.error` unless the request was aborted.
* @param opts.request The [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
* to match against.
* @param opts.requestContext An instance of {@link RouterContextProvider}
Expand Down Expand Up @@ -450,6 +451,15 @@ export async function matchRSCServerRequest({

let url = new URL(request.url);

onError ??= (error: unknown) => {
if (!request.signal.aborted) {
console.error(
// @ts-expect-error This is "private" from users but intended for internal use
isRouteErrorResponse(error) && error.error ? error.error : error,
);
}
};

basename = basename || "/";
let normalizedPath = url.pathname;
if (url.pathname.endsWith("/_.rsc")) {
Expand Down Expand Up @@ -974,6 +984,15 @@ async function generateRenderResponse(
);
}

if (staticContext.errors) {
Object.values(staticContext.errors).forEach((error) => {
// @ts-expect-error This is "private" from users but intended for internal use
if (!isRouteErrorResponse(error) || error.error) {
onError?.(error);
}
});
}

if (potentialCSRFAttackError) {
staticContext.errors ??= {};
staticContext.errors[staticContext.matches[0].route.id] =
Expand Down