Sub topic 13
Error boundaries and 404 responses
This chapter assumes you can write route modules with loaders and actions, and that you know HTTP status codes. You should also be comfortable with React components and TypeScript. By the end, you will know how thrown errors and thrown responses reach an ErrorBoundary, and how to choose where the boundary lives.
What an error boundary does
In framework mode, any route module can export a component named ErrorBoundary. React Router renders it in place of the route's normal component when something goes wrong in that route. The failures it catches are:
- An error thrown inside a
loaderoraction. - An error thrown while rendering the route's component.
- A response thrown on purpose, such as a 404.
- A request that matches no route at all.
The boundary replaces only the route that failed. Its parent layouts stay on screen, so a broken contact page can still show your navigation bar.
Throwing a 404 from a loader
A missing record is an expected case, not a crash. Signal it by throwing a response with the data helper:
import { data } from "react-router";
import type { Route } from "./+types/detail";
import { getContact } from "~/contacts.server";
export async function loader({ params }: Route.LoaderArgs) {
const contact = await getContact(params.contactId);
if (!contact) {
throw data("Contact not found", { status: 404 });
}
return { contact };
}
export default function ContactDetail({ loaderData }: Route.ComponentProps) {
return <h1>{loaderData.contact.name}</h1>;
}Throwing, instead of returning, has two benefits. The component never has to handle a missing contact, so loaderData.contact is always defined and TypeScript agrees. React Router also skips the component entirely and looks for the nearest boundary.
The two kinds of error
The boundary receives an error prop. Its value falls into one of two categories, and your code should treat them differently.
| Kind | How it arises | How to detect it | Safe to show details? |
|---|---|---|---|
| Error response | You threw `data(...)` or a `Response`. The router also produces one for an unmatched URL (404). | `isRouteErrorResponse(error)` returns `true` | Yes, you wrote the message |
| Unexpected error | A bug or failure threw an `Error`, such as a database timeout or a `TypeError` | `error instanceof Error` | No, it may leak internals |
For an error response, error.status, error.statusText, and error.data are available. Whatever you passed as the first argument to data(...) appears in error.data.
Writing a root boundary
The root route is the last line of defense. Exporting ErrorBoundary from root.tsx covers every route that has no boundary of its own, including unmatched URLs.
import { isRouteErrorResponse } from "react-router";
import type { Route } from "./+types/root";
export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
if (isRouteErrorResponse(error)) {
return (
<main>
<h1>{error.status} {error.statusText}</h1>
<p>{typeof error.data === "string" ? error.data : null}</p>
</main>
);
}
return (
<main>
<h1>Something went wrong</h1>
</main>
);
}Two details matter here. The typeof error.data === "string" check is needed because data can hold any serializable value, not only text. The fallback branch shows a generic message and never prints error.message, so internals do not reach the user.
A root boundary replaces the whole page, including the document shell you defined in root.tsx. If your root route uses a Layout export for the <html>, <head>, and <body> tags, the boundary output is wrapped by it. Without a Layout export, the boundary must render a full document itself.
Catching unmatched URLs
A URL that matches nothing in app/routes.ts does not need a special route. The router generates a 404 error response, and the root boundary renders it through the isRouteErrorResponse branch. If you prefer an explicit page, add a catch-all route as the last entry, using route("*", "routes/not-found.tsx"). Its loader or component can then throw data(null, { status: 404 }), or simply render the message while you set the status in a loader.
Choosing where the boundary lives
The nearest boundary wins. React Router starts at the route that failed and walks up the route tree until it finds a route that exports ErrorBoundary.
The diagram below shows the walk for the contacts section.
This gives you a design choice:
- A boundary on a leaf route keeps the failure local. The rest of the page, including the layout and the sidebar, keeps working.
- A boundary on a layout route handles failures from all its children with one message.
- Only the root boundary replaces the whole page.
A good default is one root boundary and one boundary on each major layout, with leaf boundaries only where a different message helps the user.
Errors in actions
Actions follow the same rules as loaders. Use the right tool for each case:
- Validation failures are expected. Return them with
data({ error }, { status: 400 })and show them next to the form, as covered in the validation chapter. - A missing or forbidden resource should be thrown, for example
throw data("Not found", { status: 404 }). The user cannot fix it by editing the form, so the boundary is the right place. - Unexpected failures can simply propagate. React Router sends them to the boundary.
Common mistakes
- Returning a 404 instead of throwing it.
return data(..., { status: 404 })hands the data to your component asloaderData, which then renders normally. Onlythrowtriggers the boundary. - Printing
error.messagefor unexpected errors. Messages from databases or libraries can contain table names, paths, or other internals. - Assuming every error is a response. Calling
error.statuswithoutisRouteErrorResponsefails type checking and crashes at runtime on a plainError. - Using a boundary for event handlers. Errors thrown in
onClickor inuseEffectare not routed to the boundary. Handle them with local state. - Forgetting the status code on the server. React Router sets the HTTP status of the document response to the thrown status. Check it with
curl -ito confirm that search engines see a real 404 and not a 200 with an error page.
Exercises
Exercise
A loader contains return data("Not found", { status: 404 }) when a record is missing, but the page shows a blank component instead of the error boundary. What is wrong, and how do you fix it?
Show answer
The loader returns the response, so it becomes loaderData and the route component renders. Change return to throw. Then React Router skips the component and renders the nearest ErrorBoundary.
Exercise
Your contacts layout route and the root route both export ErrorBoundary. The detail route does not. The detail loader throws a 404. Which boundary renders, and does the layout's navigation stay visible?
Show answer
The contacts layout boundary renders, because it is the nearest ancestor with a boundary. It renders inside the root, so the root's document shell stays. The layout's own component is replaced by its boundary, so any navigation defined in that layout component is not shown unless the boundary renders it too.
Exercise
Why should the fallback branch of a root ErrorBoundary avoid printing error.message?
Show answer
Unexpected errors come from code you did not write for display, such as database drivers. Their messages can expose internal details. Show a generic message and log the real error on the server.