How to Handle Unexpected Errors in Remix: Error Boundaries Guide
ErrorBoundary component that catches errors thrown during rendering or data loading. This component lets you show a friendly message instead of a broken page and helps you log or debug errors safely.Why This Happens
Unexpected errors in Remix occur when your code throws an error during rendering, data loading, or actions, and Remix does not have a way to catch and display them gracefully. Without handling, users see a blank page or a generic error, which is confusing.
export default function MyComponent() { // This will throw an error if data is missing const data = null; return <div>{data.title.toUpperCase()}</div>; }
The Fix
Wrap your component or route with an ErrorBoundary export. Remix will use this to catch errors and render a fallback UI. This prevents the app from crashing and shows a helpful message.
import { useRouteError } from "@remix-run/react"; export function ErrorBoundary() { const error = useRouteError(); console.error(error); return ( <div role="alert"> <h1>Something went wrong</h1> <p>{error?.message || "An unexpected error occurred."}</p> </div> ); } export default function MyComponent() { const data = null; return <div>{data.title.toUpperCase()}</div>; }
Prevention
To avoid unexpected errors, always validate your data before using it and provide default values. Use TypeScript or runtime checks to catch issues early. Implement ErrorBoundary in every route to catch errors gracefully. Use logging services to track errors in production.
Related Errors
Other common errors include Loader errors when data fetching fails and Action errors during form submissions. These can also be caught by ErrorBoundary or handled with catchBoundary for expected errors like 404 or validation failures.